[英]ng-model is undefined from controller
Hi, 嗨,
Why the value from foo()
function is undefined? 为什么来自
foo()
函数的值是未定义的?
I found that the problem is if the model name is only brand
but, it is not my problem. 我发现问题是如果型号名称只是
brand
,但这不是我的问题。 The name of my model is car.brand
. 我的模型名称是
car.brand
。
So my question is - how to access model from ctrl? 所以我的问题是 - 如何从ctrl访问模型?
HTML : 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 : JS :
$scope.foo = function() {
alert("foo: " + $scope.car.brand);
}
Thanks. 谢谢。
As you are using ng-repeat
, you will have many cars, so your model you be filled in the cars: 当您使用
ng-repeat
,您将拥有许多汽车,因此您可以在汽车中填充您的模型:
$scope.foo = function() {
for(var i in $scope.cars) {
alert("foo: " + $scope.cars[i].brand);
}
}
You need to use car.brand as
or car.model as
你需要使用
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>
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 无论是之前的
as
是价值ng-model
将得到
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.