我正在尝试执行多列操作(最终基于用户选择),其中每列都独立于其余列随机化其结果。这意味着我不确定会有多少列,并且我希望能够根据需要重复该函数。我知道在 PHP 中有一种方法可以做到这一点(类似于 $var{$i}, iirc),但是我如何在 Angular 中做到这一点?
html 看起来像这样:
<tr>
<td><button ng-click="rollDice1(1)">rand 1</button></td>
<td><button ng-click="rollDice2(2)">rand 2</button></td>
<td><button ng-click="rollDice3(3)">rand 3</button></td>
</tr>
<tr>
<td>{{animal1}}</td>
<td>{{animal2}}</td>
<td>{{animal3}}</td>
</tr>
现在,在我的 Controller 中,我必须为每个 Controller 执行一个操作,这就是为什么有 rollDice1、rollDice2 等。它们看起来像这样:
$scope.rollDice1 = function () {
$scope.animal1 = animalRand();
$scope.color1 = colorRand();
$scope.size1 = sizeRand();
$scope.age1 = randFloor(15, 1);
};
所以有一个rollDice2,它给我animal2、color2等,然后是一个rollDice3,等等。不过,我想做的只是拥有一个,并根据输入的值更改变量名称,但我不知道如何让它发挥作用。当前版本是:
$scope.rollDice = function (val) {
$scope.animal[val] = animalRand();
$scope.color[val] = colorRand();
$scope.size[val] = sizeRand();
$scope.age[val] = randFloor(15, 1);
};
我尝试过其他一些,例如 $scope.animal.val,甚至 $scope.animal{val},但这些只会向我抛出错误。有没有办法做到这一点,或者我是否坚持为每个函数制作一个单独的函数,并限制用户的选项?
Plnkr 在这里:http://plnkr.co/edit/J0mYup?p=preview
提前致谢!
最佳答案
您需要使用数组访问器表示法,并使用从值构建的字符串键。您的 rollDice
函数应如下所示:
$scope.rollDice = function (val) {
$scope["animal" + val] = animalRand();
$scope["color" + val] = colorRand();
$scope["size" + val] = sizeRand();
$scope["age" + val] = randFloor(15, 1);
};
然后您可以在模板代码中使用 rollDice(1)
、rollDice(2)
等调用它。
如果您有很多这样的数据,将数据存储在数组中可能更有意义。您可以在范围上创建一个数组,如下所示:
$scope.data = [];
然后,您的 rollDice
函数将如下所示:
$scope.rollDice = function (val) {
$scope.data[val] = {
animal: animalRand(),
color: colorRand(),
size: sizeRand(),
age: randFloor(15, 1),
};
};
您仍会以相同的方式调用 rollDice
,但随后您将使用不同的方法从 HTML 模板访问范围数据。
<tr>
<td>{{data[1].animal}}</td>
<td>{{data[2].animal}}</td>
<td>{{data[3].animal}}</td>
</tr>
这还有一个额外的优势,那就是使用 ngRepeat
之类的东西来实现自动化。 。例如,该代码可以简化为:
<tr>
<td ng-repeat="item in data">{{item.animal}}</td>
</tr>
关于javascript - 根据输入使变量名动态化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28143140/