ng-модель не определена из контроллера

играть на скрипке

Привет,

Почему значение от foo() функция не определена?

Я обнаружил, что проблема в том, что если название модели brand но это не моя проблема. Название моей модели car.brand,

Итак, мой вопрос - как получить доступ к модели из Ctrl?

HTML:

<div ng-controller="MyCtrl">
  <div ng-if="cars" ng-repeat="car in cars">
    <br>
    <label>{{car.name}}</label>
    <br>
    <label>brand</label>
    <select ng-model="car.brand" ng-options="car as car.name for car in brands" ng-change="loadBrands($index)">
      <option value="">select</option>
    </select>
    <label>model</label>
    <select ng-model="brand.model" ng-options="car as car.model for car in cars[$index].models">
      <option value="">select</option>
    </select>

  </div>
  <button ng-click="foo()">
    save all
  </button>
</div>

JS:

$scope.foo = function() {
   alert("foo: " + $scope.car.brand);
 }

Благодарю.

2 ответа

Решение

Как вы используете ng-repeat, у вас будет много машин, поэтому ваши модели вам заправят в авто:

$scope.foo = function() {
   for(var i in $scope.cars) {
     alert("foo: " + $scope.cars[i].brand);
   }   
}

Вам нужно использовать car.brand as или же car.model as

<div ng-controller="MyCtrl">
  <div ng-if="cars" ng-repeat="car in cars">
    <br>
    <label>{{car.name}}</label>
    <br>
    <label>brand</label>
    <select ng-model="car.brand" ng-options="car.brand as car.name for car in brands" ng-change="loadBrands($index)">
      <option value="">select</option>
    </select>
    <label>model</label>
    <select ng-model="brand.model" ng-options="car.model as car.model for car in cars[$index].models">
      <option value="">select</option>
    </select>

  </div>
  <button ng-click="foo()">
    save all
  </button>
</div>

или сделать

<div ng-controller="MyCtrl">
  <div ng-if="cars" ng-repeat="car in cars">
    <br>
    <label>{{car.name}}</label>
    <br>
    <label>brand</label>
    <select ng-model="car" ng-options="car as car.name for car in brands" ng-change="loadBrands($index)">
      <option value="">select</option>
    </select>
    <label>model</label>
    <select ng-model="brand" ng-options="car.brand as car.model for car in cars[$index].models">
      <option value="">select</option>
    </select>

  </div>
  <button ng-click="foo()">
    save all
  </button>
</div>

что бы ни было до as это значение ng-model получите

Другие вопросы по тегам