有没有办法在不使用ng-change的情况下使用ng-options更新两个值?

时间:2016-10-26 22:59:41

标签: javascript angularjs

我有一个下拉列表,我想在选择其中一个选项时更新对象。如果我只需要更新对象的单数属性,这很好,但在这种情况下,我想使用对象下拉列表中的两个属性更新两个属性。

我可以直接将选项分配给对象,但后来我丢失了我要保留的属性名称。

我找到了一种使用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>

https://plnkr.co/edit/di7RB2oVKJR57CK1sOPh?p=preview

2 个答案:

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

Plunker:http://plnkr.co/edit/oKfWRANkkPiS6UHKrjRX

答案 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将用于观看和更新属性。
  • watch-var:会关注item.number的更改。
  • update-var:更新name的{​​{1}}属性。
  • list-name: item将用于映射。