2014-02-11 34 views
1

当我改变一个select时,它会触发其他使用相同指令的选择的所有方法绑定。这是预期的行为?例如,如果我改变状态选择,它会触发选中的状态,也会选择狗。我错过了对Angular Directives的基本理解?我注意到如果我没有指示就这样做,这不是行为。Angular指令方法绑定ng-select

这里是我的plunkr:http://plnkr.co/edit/inKtjY?p=preview

var app = angular.module('app', []); 

    app.controller('controller', function ($scope) { 

     $scope.firstName = "Michael"; 

     $scope.states = [{ id: 1, name: 'Nebraska' }, { id: 2, name: 'Iowa' }]; 
     $scope.state = $scope.states[0]; 
     $scope.stateselected = function (state) { 

      console.log('state selected:', state); 
     }; 


     $scope.dogs = [{ id: 11, name: 'Poodle' }, { id: 12, name: 'Pitbull' }]; 
     $scope.dog = $scope.dogs[0]; 
     $scope.dogselected = function (dog) { 

      console.log('dog selected:', dog); 
     }; 
    }); 

    app.directive('myselect', function() { 

     return { 
      restrict: 'E', 
      template: '<select ng-model="item" ng-options="i as i.name for i in itemlist " ng-selected="itemselected()"></select>', 
      scope: { 
       item: '=', 
       itemlist: '=', 
       itemselected: '&' 
      } 
     }; 
    }); 

HTML

<div ng-controller="controller"> 

    State:<myselect item='state' itemlist='states' itemselected='stateselected(state)'></myselect><br> 

    Dogs: <myselect item='dog' itemlist='dogs' itemselected='dogselected(dog)'></myselect><br> 

</div> 

回答

0

看起来你正在寻找的ngChange指令不ngSelected。尝试修改您的指令模板是:

<select ng-model="item" ng-options="i as i.name for i in itemlist" ng-change="itemselected()"></select> 

现在你会发现,当你ngModel的值被改变了你的函数被调用。如果要在<option>元素上使用ngRepeat指令(而不是使用ngOptions),则可以在<option>元素上的ngSelected中表达一个表达式,该元素将用于确定当前选中哪个选项。

ngSelected发生这种情况的原因是因为该指令期望表达式进行评估。你传递了一个函数(这非常好),所以无论何时你要更新<select>中的选择,它都会强制一个Angular digest循环(因为你的ngModel正在被更改)。它最终会达到您的ng-selected="itemselected()"表达式,并尝试通过执行它来对其进行评估。

+0

我确实尝试使用ng-changed,并且我注意到它在事件实际更改之前触发了事件。我感谢你的回应,因为它让我可以查看和了解这个摘要。我认为有更好的方法来做到这一点与$ watch,但我虽然这个简单的解决方案将工作.. – Maccurt