我正在尝试使用循环简化脚本,但我无法使其工作。
我想转换以下工作代码,并将其缩短以显示/隐藏div。
var app = angular.module('myApp', ['ngAnimate']);
app.controller('onderdelenCtrl', function($scope) {
$scope.spec1 = true;
$scope.spec2 = true;
$scope.spec3 = true;
...
$scope.spec9 = true;
$scope.togglespec1 = function() {
$scope.spec1=!$scope.spec1; }
$scope.togglespec2 = function() {
$scope.spec2=!$scope.spec2; }
$scope.togglespec3 = function() {
$scope.spec3=!$scope.spec3; }
...
$scope.togglespec9 = function() {
$scope.spec9=!$scope.spec9; }
});
类似于:
var onderdelenlijst = ["processor", "moederbord", "video", "opslag", "geheugen", "behuizing", "voeding", "dvd", "geluid"];
var indexonderdelenlijst = onderdelenlijst.length;
var app = angular.module('myApp', ['ngAnimate']);
app.controller('onderdelenCtrl', function($scope) {
i=0;
while (i < indexonderdelenlijst) {
i++;
var spec = $scope.spec + i;
spec = true;
togglespec = $scope.togglespec + i;
togglespec = function() {
spec =! spec; }
}
});
我不知道自己做错了什么,我已经尝试了多种方法,但它仍然以某种方式失败。
答案 0 :(得分:1)
您应该使用数组作为规范,并使用索引作为参数的切换函数。
var onderdelenlijst = ["processor", "moederbord", "video", "opslag", "geheugen", "behuizing", "voeding", "dvd", "geluid"];
var indexonderdelenlijst = onderdelenlijst.length;
var app = angular.module('myApp', ['ngAnimate']);
app.controller('onderdelenCtrl', function($scope) {
$scope.spec = [];
for(var i = 0; i < indexonderdelenlijst; i++) {
$scope.spec.push(true);
}
$scope.togglespec = function(index) {
$scope.spec[index] = !$scope.spec[index];
}
});
答案 1 :(得分:1)
您不需要js代码来切换div。
Html就足够了。
<div ng-show="showdiv1" ng-click="showdiv1=!showdiv1"></div>
<div ng-show="showdiv2" ng-click="showdiv2=!showdiv2"></div>
答案 2 :(得分:1)
就像一个例子,也许是这样的?
JS
$scope.specs = [0, 1, 2, 3];
$scope.toggle = function (index) {
$scope.specs[index] = !$scope.specs[index];
}
标记
<div ng-repeat="spec in specs">
<button ng-click="$scope.toggle($index)">Toggle</button>
</div>
答案 3 :(得分:1)
如果您继续 $ scope 变量,则应用此方法 使用它:
$scope['spec'+i];
不
var spec = $scope.spec + i;
$ scope ['spec'+ i]; 在所有获得$ scope变量的地方继续使用...