似乎是个简单的问题,但实际上我遇到了麻烦。
基本上,我有一个纳克重复按钮,然后一个文本块之后,点击按钮将显示。但是,当我单击一个按钮时,我希望隐藏所有其他按钮中的文本块,并从其他按钮中删除活动状态。基本上一次只显示一个按钮块的文本。
看起来很容易,但是ng隐藏处理作用域(作用域: true)的方式意味着我不能真正地查看其他作用域并关闭它们。另一件事是,如果可能的话,我不想改变实际数组的ng-重复。这是我必须返回的API中的数据,如果可以的话,我将尝试不改变实际的数据结构。
<div class="row" ng-repeat="button in buttons">
<div class="col-sm-2">
<button ng-click="showInfo = !showInfo" class="btn btn-primary">{{button.name}}</button>
</div>
<div ng-show="showInfo" class="col-sm-3">
<div class="alert alert-success">{{button.extraInfo}}</div>
</div>
</div>和JS
app.controller('MainCtrl', function($scope) {
$scope.buttons = [
{ name: 'One', extraInfo: 'Extra info for button 1' },
{ name: 'Two', extraInfo: 'Extra info for button 2' },
{ name: 'Three', extraInfo: 'Extra info for button 3' }
];
});发布于 2015-02-11 19:15:29
我建议创建与buttons数组长度相同的新数组,该数组将保存布尔值,以指示项目活动与否。
我没有登录,所以在这里修改了你的版本。
index.html
<body ng-controller="MainCtrl as vm">
<div class="row" ng-repeat="button in buttons track by $index">
<div class="col-sm-2">
<button ng-click="vm.setActive($index)" ng-class="vm.isActive[$index] ? 'btn btn-primary' : 'btn'">{{button.name}}</button>
</div>
<div ng-show="vm.isActive[$index]" class="col-sm-3">
<div class="alert alert-success">{{button.extraInfo}}</div>
</div>
</div>
</body>app.js
app.controller('MainCtrl', function($scope) {
$scope.buttons = [
{ name: 'One', extraInfo: 'Extra info for button 1' },
{ name: 'Two', extraInfo: 'Extra info for button 2' },
{ name: 'Three', extraInfo: 'Extra info for button 3' }
];
var vm = this;
vm.isActive =[];
for(var i=0, len=$scope.buttons.length; i < len; i++){
vm.isActive[i] = false;
}
vm.setActive = function(ind) {
for(var i=0, len=vm.isActive.length; i < len; i++){
vm.isActive[i] = i===ind;
}
}
});发布于 2015-02-11 19:46:25
如果不想更改实际数组,则维护另一个对象或数组,该对象或数组将保存每个按钮的显示/隐藏状态的键。
$scope.showInfo = {};
$scope.buttons = [
{ name: 'One', extraInfo: 'Extra info for button 1' },
{ name: 'Two', extraInfo: 'Extra info for button 2' },
{ name: 'Three', extraInfo: 'Extra info for button 3' }
];
$scope.changeShowInfo = function(index) {
for(var prop in $scope.showInfo) {
$scope.showInfo[prop] = false;
}
$scope.showInfo[index] = true;
};发布于 2015-02-11 19:29:51
您希望每次活动一个按钮,所以最好使用带有currentItem的单选按钮,方法是使用ng绑定。
HTML:
<body ng-controller="MainCtrl">
<div name="myForm">
<div ng-repeat="button in buttons">
<label>
<input type="radio" ng-model="$parent.selectedItem" ng-value="button"> {{button.name}}
</label>
</div>
</div>
<div class="alert alert-success">Extra info: {{selectedItem.extraInfo}}</div>
</body>不需要改变你的JS。
https://stackoverflow.com/questions/28461181
复制相似问题