我正在尝试使用ng-options预选值。这是什么
<select ng-model="promocode.PRODUCT" ng-change="getSomething()" ng-options="product as product.NAME for product in products">
问题是默认值选中。我的promocode.PRODUCT
对象与ng-options中的对象相同,但角度设置默认值为空。
我的错误在哪里?
答案 0 :(得分:2)
假设您的产品具有某种id
属性,这应该可以解决问题:
<select ng-model="promocode.PRODUCT"
ng-change="getSomething()"
ng-options="product as product.NAME for product in products track by product.id">
track by product.id
告诉angular用它们的id
属性比较数组项,而不是比较对象之间的相等性。
以下是tracking / ng-options的更多信息。
一个有效的例子:
var myApp = angular.module('myApp', []);
myApp.controller("controller", function($scope) {
$scope.products = [{
id: 1,
name: 'FirstProduct'
}, {
id: 2,
name: 'SecondProduct'
}];
$scope.promocode = {
product: { // Here I am using a placeholder product to illustrate that
id: 2 // the select is identifying the correct row by it's `id`.
}
};
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="controller">
<select ng-model="promocode.product" ng-change="getSomething()" ng-options="product as product.name for product in products track by product.id">
</select>
<br/>
{{promocode.product}}
</div>
&#13;
更好的选择是选择正确的行,如下所示:
$scope.promocode = $scope.products[1];
然后你不必复制任何数据。
答案 1 :(得分:1)
假设log4j.additivity=false
有product
属性,您需要使用id
,阅读DOCs
select as label group by group for value in array track by trackexpr
答案 2 :(得分:0)
试试这个..
<select ng-model="promocode.PRODUCT"
ng-change="getSomething()"
ng-options="product as product.NAME for product in products track by product.ID">
<option selected disabled>{{Your default value}}</option>
</select>