我有一个下拉列表,我想在选择其中一个选项时更新对象。如果我只需要更新对象的单数属性,这很好,但在这种情况下,我想使用对象下拉列表中的两个属性更新两个属性。
我可以直接将选项分配给对象,但后来我丢失了我要保留的属性名称。
我找到了一种使用ng-change和下划线来查找关联值的方法,但是如果我的页面上有很多下拉列表,那么每个下拉列表执行此操作会很麻烦(我计划在做)。
有没有办法只使用ng-options来做同样的功能?如果没有,是否有更好的方法,所以我不必为每次下拉重复更新功能?
JS
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.list = [
{value: '1', text: 'joe'},
{value: '2', text: 'bill'},
{value: '3', text: 'ted'},
];
//I want to keep the property names, notice how value matches with number
//and text matches with name
$scope.item = {
name: 'joe',
number: '1'
}
//Is there a way to get this same functionality using ng-options?
$scope.update = function(item) {
item.name = _.findWhere($scope.list, {value: item.number}).text;
}
});
HTML
<select ng-model="item.number"
ng-options="option.value as option.text for option in list" ng-change="update(item)">
</select>
答案 0 :(得分:1)
是的,有。您可以直接对$scope.item
使用ng-model
对象,并使用预期的对象格式({name: option.text, number: option.value}
)作为ng-options
中的值,按唯一属性进行跟踪,然后让Angular做其余的事。
track by option.value || option.number
是必要的,以匹配初始呈现的选择,$scope.item
最初没有item.value
进行比较,因此track by
将回退到item.number
进行比较。
<强> JS 强>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.list = [
{value: '1', text: 'joe'},
{value: '2', text: 'bill'},
{value: '3', text: 'ted'},
];
$scope.item = {
name: 'joe',
number: '1'
}
});
<强> HTML 强>
<select ng-model="item"
ng-options="{name: option.text, number: option.value} as option.text
for option in list
track by option.value || option.number"></select>
{{item.name}}-{{item.number}}
答案 1 :(得分:1)
当项目编号的值发生变化时,您可以创建指令来更新模型。
更新了您的Plunker code
<强>指令:强>
app.directive('customModel', function() {
return {
restrict: "A",
link: function(scope, ele, attr) {
scope.$watch(attr.customModel+"."+attr.watchVar, function(new_value){
scope[attr.customModel][attr.updateVar] = _.findWhere(scope[attr.listName], {value: new_value}).text;
});
}
};
});
<强>模板:强>
<select custom-model="item" watch-var="number" update-var="name" list-name="list" ng-model="item.number" ng-options="option.value as option.text for option in list1"></select>
由于您将在单个页面中拥有多个<select>
,因此我添加了其他属性来提及要更新的变量:
item
将用于观看和更新属性。item.number
的更改。name
的{{1}}属性。item
将用于映射。