所以我在获得适当的视觉反馈以及我想要的数据绑定行为方面遇到了问题。这是我的代码:
<div ng-app="myTestApp" ng-controller="myTestCtrl">
<!-- selected value is site.name -->
<h3>Selected value is site.name property</h3>
<select ng-model="testSelect" ng-options="site.name as site.name for site in sites track by site.name">
<option value="">Please choose a site</option>
</select>
<div ng-bind="testSelect"></div>
<hr/>
<!-- Selected value is site object itself -->
<h3>Selected value is the site object itself</h3>
<select ng-model="testSelectTwo" ng-options="site.name for site in sites track by site.name">
<option value="">Please choose a site</option>
</select>
<div ng-bind="testSelectTwo"></div>
</div>
这里附带有角度的javascript:
var app = angular.module('myTestApp', []);
app.controller('myTestCtrl', ['$scope', function ($scope) {
$scope.sites = [
{id: 1, name: 'Site 1', link: 'http://url'},
{id: 2, name: 'Site 2', link: 'http://url'},
{id: 3, name: 'Site 3', link: 'http://url'}
];
}]);
以上所有的jsFiddle:http://jsfiddle.net/aZwLY/
现在我想要的是ng-model给出了我使用的site.name属性(使用上面代码的jsFiddle示例的上半部分),但我也想要实际选择更改的视觉反馈(bottom一半的jsFiddle例子。)
到目前为止,我还没有想过解决方案。
答案 0 :(得分:1)
删除track by
条款。这就是造成问题的原因
跟踪依据是您可能有不同的对象应该被视为等于。要使用您的第二个示例,如果我执行了以下操作:
$scope.site = {id: 1, name: "Site 3", link: ""};
它会使ID为3的网站被选中。这是因为我们跟踪名称。