我有一个值,并希望在select下拉列表中预先选择它。复杂的是模型是一个对象而不是一个简单的字符串。我尝试使用track by但似乎没有解决问题...也许你可以帮忙吗?
让我们假设控制器加载时javascript中的模型:
$scope.condition = {name: 'blah', value: '{"id":2,"value":"Monthly Flyer"}' }
$scope.options = [
{"id":1,"value":"Winter Catalog"},
{"id":2,"value":"Monthly Flyer"},
{"id":3,"value":"Sample Catalog"},
{"id":4,"value":"Senior Living"},
...]
注意第二个对象与第一个对象相同...但是,从技术上讲,它会有不同的对象引用,所以
angular.toJson($scope.condition) === angular.toJson(options[1])
是true
但
$scope.condition === options[1]
为false
这是代码
<select class="form-control" ng-model="condition.value"
ng-options="opt as (opt.value + ' [' + opt.id + ']')
for opt in options.picklistOptions track by opt.id"></select>
为什么你认为它没有加载?
答案 0 :(得分:1)
好吧,我不确定你要做什么,但我认为你有一个对象保存在某个地方,你想根据这个选择<option>
。
然后,如果我纠正了你就错误地将ng-model设置为condition.value
而不仅仅是condition
。
看到它正常工作:
(function() {
"use strict";
angular.module('app', [])
.controller('mainCtrl', function($scope) {
$scope.options = {};
$scope.options.picklistOptions = [
{
"id":1,
"value":"Winter Catalog"
},
{
"id":2,
"value":"Monthly Flyer"
},
{
"id":3,
"value":"Sample Catalog"
},
{
"id":4,
"value":"Senior Living"
}
];
$scope.condition = {
"id":2,
"value":"Monthly Flyer"
};
});
})();
&#13;
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<select class="form-control" ng-model="condition" ng-options="opt as (opt.value + ' [' + opt.id + ']') for opt in options.picklistOptions track by opt.id"></select>
<hr>
<span ng-bind="condition | json"></span>
</body>
</html>
&#13;
答案 1 :(得分:-1)
试试这个:
angular.module('app', [])
.controller('Controller', ['$scope', function($scope) {
$scope.listOptions = [
{id:1,value:"Winter Catalog"},
{id:2,value:"Monthly Flyer"},
{id:3,value:"Sample Catalog"},
{id:4,value:"Senior Living"}
];
}]);
&#13;
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"> </script>
</head>
<body ng-controller="Controller">
<select class="form-control" ng-model="obj_options" ng-options="item as item.value for item in listOptions"></select>
<span>{{obj_options.value}}</span>
</body>
</html>
&#13;