考虑一个简单的ng-repeat,它在每次迭代中创建一个指令。每个指令都包含一个触发函数的按钮。这些按钮的标签应设置为“显示”,单击按钮时应更改为“隐藏”。当我点击一个按钮时,我想检查是否有其他按钮设置为“隐藏”:如果是,它们应该恢复为“显示”。基本上我的目标是只有一个按钮,标签设置为“隐藏”,其他按钮应始终为“显示”。我怎么能这样做?
<div ng-repeat="campaign in $root.transactions">
<my-directive campaign='campaign' index='$index></my-directive>
</div>
myDirective.html:
<div>
..some stuff...
<button ng-click="toggleDetail()">{{labelButton}}</button>
</div>
JS:
$scope.labelButton = 'Show';
$scope.detailOpened = false;
$scope.labelButton = 'Show';
$scope.$root.selectedIndex = -1;
$scope.toggleDetail = function($event, index){
...do stuff...
$scope.detailOpened = !$scope.detailOpened;
$scope.$root.selectedIndex = index;
$(element).toggleClass('selectedActivity');
if($scope.detailOpened === false) {
$scope.labelButton = 'Show';
}else {
$scope.labelButton = 'Hide';
}
};
答案 0 :(得分:1)
使用ng-repeat,您需要$ scope范围内的数组。使用指令可以,但可能没有必要。
我在这里制作了一个jsfiddle:http://jsfiddle.net/goodman/z9kg0md0/15/embedded/result/
我想知道这是不是你想要的。代码在这里:
null
和html:
angular.module("MyApp",[])
.controller( 'myController', [ '$scope', function( $scope ){
$scope.buttons = [
{ detailOpened: false, label: 'Show1'},
{ detailOpened: false, label: 'Show2'},
{ detailOpened: false, label: 'Show3'},
{ detailOpened: false, label: 'Show4'},
{ detailOpened: false, label: 'Show5'}
];
$scope.toggleDetail = function(index){
$scope.buttons[index].detailOpened = !$scope.buttons[index].detailOpened;
if(!$scope.buttons[index].detailOpened) {
$scope.buttons[index].label = 'Show';
}else {
$scope.buttons[index].label = 'Hide';
}
if( $scope.buttons[index].detailOpened ){
for( var i = 0; i < $scope.buttons.length ; i++ ){
if( i != index && $scope.buttons[i].detailOpened) {
$scope.buttons[i].detailOpened = false;
$scope.buttons[i].label = 'Show';
}
}
}
};
}]);