1

fiddle

Hi,

Why the value from foo() function is undefined?

I found that the problem is if the model name is only brandbut, it is not my problem. The name of my model is car.brand.

So my question is - how to access model from 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);
 }

Thanks.

user3700786
  • 149
  • 1
  • 13

2 Answers2

0

As you are using ng-repeat, you will have many cars, so your model you be filled in the cars:

$scope.foo = function() {
   for(var i in $scope.cars) {
     alert("foo: " + $scope.cars[i].brand);
   }   
}
Diego Polido Santana
  • 1,425
  • 11
  • 19
0

You need to use car.brand as or 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>

or do

<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>

whatever is before the as is the value the ng-model will get

Steven Kaspar
  • 1,147
  • 10
  • 14