我有一个下拉列表,当其中一个选项被选中时,我想更新一个对象。如果我只需要更新对象上的单个属性,这很好,但在本例中,我想使用对象下拉列表中的两个属性来更新两个属性。
我可以直接将选项赋值给对象,但这样我就失去了我想保留的属性名称。
我想出了一种方法,使用ng-change和underscore来找到相关的值,但是如果我的页面上有很多下拉列表(我计划这样做),那么对每个下拉列表执行此操作就会变得乏味。
是否有任何方法可以使用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>
https://plnkr.co/edit/di7RB2oVKJR57CK1sOPh?p =预览
是的,有。你可以直接在ng-model
中使用$scope.item
对象,在ng-options
中使用预期的对象格式({name: option.text, number: option.value}
)作为值,通过一个唯一的属性进行跟踪,然后让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'
}
});