[英]Making variable name dynamic based on input?
我正在尝试做多列(最终基于用户选择),其中每一列将其结果独立于其余部分而随机分配。 这意味着我不确定是否会有多少列,并且我希望能够根据需要重复该功能。 我知道有一种方法可以在PHP中执行此操作(类似于$ var {$ i},iirc),但是我该怎么做呢?
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>
在我的控制器中,现在,我必须为每个控制器做一个,这就是为什么要有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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.