我是AngularJS的新手,我正在尝试定义4个单独的选择元素usign元素指令。
app.directive('playerselect', function() {
return {
restrict: 'E',
replace: true,
templateUrl: 'templates/directives/player-select.html',
}
});
<select ng-options="player.full_name for player in players">
<option value="" selected disabled>Kies een speler</option>
</select>
当用户选择其中一个选择元素中的选项时,我希望更新其他选择元素,以便在所有其他选择元素中禁用所选选项。基本上,我想确保每个选项只能选择一次。
关于如何做到这一点的任何想法?
答案 0 :(得分:4)
我会这样做:
指令
app.directive('playerSelect', function() {
return {
templateUrl: ...
scope: {
players: '=',
selectedPlayer: '=',
selectedPlayers: '=',
},
controller: function($scope) {
$scope.isDisabled = function(player) {
return $scope.selectedPlayers.indexOf(player) > -1 &&
player !== $scope.selectedPlayer)
};
},
}
});
指令模板
<select ng-model="selectedPlayer">
<option ng-repeat="player in players" ng-disabled="isDisabled(player)">{{player}}</option>
</select>
控制器
app.controller('PlayerController', function($scope) {
$scope.players = ...
$scope.selectedPlayers = [
$scope.player1,
$scope.player2,
$scope.player3,
$scope.player4,
];
});
控制器模板
<div ng-controller="PlayerController">
<player-select players="players" selected-players="selectedPlayers" selected-player="player1"></player-select>
<player-select players="players" selected-players="selectedPlayers" selected-player="player2"></player-select>
<player-select players="players" selected-players="selectedPlayers" selected-player="player3"></player-select>
<player-select players="players" selected-players="selectedPlayers" selected-player="player4"></player-select>
</div>
答案 1 :(得分:1)
检查此 jsFiddle 是否有效。
我建议您使用directive two way data binding和ngModelController。
所以在你的HTML中:
<player-select players="players" ng-model="select1"></player-select>
<player-select players="players" ng-model="select2"></player-select>
<player-select players="players" ng-model="select3"></player-select>
在您的控制器中:
$scope.players = [{
name: 'foo'
}, {
name: 'bar'
}, {
name: 'baz'
}];
指令,使用scope.$watch
更新每个列表:
angular.module('fiddleApp').directive('playerSelect', function ($rootScope) {
return {
restrict: 'E',
require: 'ngModel',
scope: {
players: '='
},
template: '<select ng-model="selected" ng-options="player.name for player in playersCopy"></select>',
link: function (scope, el, attrs, ngModel) {
function update() {
scope.playersCopy = angular.copy(scope.players);
if (scope.selected) {
scope.playersCopy.push(scope.selected);
}
}
scope.$watch('selected', function (newValue, oldValue) {
if (newValue) {
scope.players.splice(scope.players.map(function (a) {
return a.name
}).indexOf(newValue.name), 1);
if (oldValue) { scope.players.push(oldValue); }
ngModel.$setViewValue(scope.selected);
$rootScope.$broadcast('playersUpdate');
}
});
scope.$on('playersUpdate', function () {
update();
});
update();
}
};
});