當我改變一個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>
我確實嘗試使用ng-changed,並且我注意到它在事件實際更改之前觸發了事件。我感謝你的迴應,因爲它讓我可以查看和了解這個摘要。我認爲有更好的方法來做到這一點與$ watch,但我雖然這個簡單的解決方案將工作.. – Maccurt