<div ng-app="myApp">
<div ng-controller='Ctrl'>
<select id="tradestyle" ng-model="currentTradestyle" update-model="tradestyles">
<option ng-repeat="style in tradestyles" value="{{style.id}}">{{style.name}}</option>
</select>
<input type="text" ng-model="currentTradestyle.name" />
</div>
</div>
JavaScript:
var app = angular.module('myApp', []);
app.controller('Ctrl', ['$scope', '$rootScope', function ($scope, $rootScope) {
$scope.tradestyles = [{
"id": "1",
"source": "Source One",
"name": "Name One"
}, {
"id": "2",
"source": "Source Two",
"name": "Name Two"
}];
}]);
app.directive('updateModel', function() {
return {
require: '?ngModel',
restrict: 'A',
link: function(scope, element, attrs, modelCtrl) {
function parser(value) {
if(value) {
return _.findWhere(scope[attrs.updateModel], {id: value});
}
}
modelCtrl.$parsers.push(parser);
},
}
});
这可能会满足您在评论中提出的问题。它在 s 中使用 tradestyle.id 而不是 $index,<option>这意味着所选项目在将过滤器应用于集合的情况下有效。附加的 $parser 确保 tradestyle.id 在应用于 currentTradestyle 模型属性之前实际上成为选定的贸易风格项目。
存在对 Underscore 的依赖,但您可以使用 findWhere() 方法的更长时间的替代方法来删除它。
http://jsfiddle.net/asperry1/Zfecq/6/