有没有一种方法可以使用ng-options而不使用ng-change来更新两个值?



我有一个下拉列表,当其中一个选项被选中时,我想更新一个对象。如果我只需要更新对象上的单个属性,这很好,但在本例中,我想使用对象下拉列表中的两个属性来更新两个属性。

我可以直接将选项赋值给对象,但这样我就失去了我想保留的属性名称。

我想出了一种方法,使用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'
  }
});

<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}}

砰砰作响:http://plnkr.co/edit/oKfWRANkkPiS6UHKrjRX

您可以创建指令,以便在项目编号的值发生变化时更新模型。

更新你的Plunker代码

指令:

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>,因此我包含了额外的属性以提及要更新的变量:

  • custom-model: item将用于监视和更新属性。
  • watch-var:将监视item.number的变化。
  • update-var:更新itemname属性。
  • list-name: list将用于映射

最新更新