【发布时间】:2014-09-12 20:49:43
【问题描述】:
我有一个指令,它使用id 参数在控制器的范围内获取一个数组,如果 id 是静态值,它可以正常工作,但是如果我使用花括号(例如,我使用 ng-repeat 重复指令所以每个 id 都需要是唯一的,尽管如果我使用另一个属性而不是 id 它仍然不起作用),那么它就不起作用,大括号不被评估,并在网络检查器中查看源代码,它字面意思是id={{index}},而不是id=1。
编辑: 我想要做的是当 html 中有一个 stack 元素时,它会在当前范围(不是指令的范围)中创建一个与 id 同名的变量。
app.directive('stack', function() {
return {
restrict: 'E',
templateUrl: 'stack.html',
scope: {
cards: '=id',
name: '@id',
countOnly: '@'
},
link: function(scope) {
scope.cards = [];
//because of cards: '=id', scope.cards is bound to the parentscope.<value of id attr>, so setting scope.cards to [], also creates the variable in the parent scope.
}
};
});
stack.html 模板仅包含(目前将在稍后展开):
<div class="stack">The stack called {{name}} contains {{cards.length}} cards</div>
如果我的 index.html 中有这个:
<stack id="deck"></stack>
<span>There are {{deck.length}} cards in deck</span>
结果是:
The stack called deck contains 0 cards
There are 0 cards in deck
(如果我要在牌组数组中添加一张牌,那么两个零都会变成一个)
上面的工作,因为它不使用 ng-repeat,属性是硬编码的。下面的属性需要是动态的,这不起作用,因为不计算花括号。
但是,如果我想通过使用 ng-repeat 来拥有多个卡组,则它不起作用:
<stack ng-repeat="index in range(5)" id="slot{{index}}"></stack>
那么 id 仍然是字面上的“slot{{index}}”,而不是“slot0”等。
我能做到:
<stack id="slot0"></stack>
<stack id="slot1"></stack>
<stack id="slot2"></stack>
<stack id="slot3"></stack>
<stack id="slot4"></stack>
它会按我的预期工作。
这几乎就像我需要 cards: '=id', 成为 cards: '=$parse(id)',(或者可能只在它包含大括号时才解析)
【问题讨论】:
-
您在您的一个 cmets 中提到
range function returns ["slot1", "slot2",...]但在您上面的声明中提到它返回一系列数字?那是哪一个? -
它是数字,但在我的评论中我说“说范围函数返回......”,因为该评论更方便。
-
hmm 让我直截了当,您希望
scope.cards作为range()函数返回数组的引用,而您希望scope.name成为该数组的项? -
能否请您也发布您的控制器代码,您从哪里得到“名为deck 的堆栈包含0 张卡片”,{{name}} = “deck”?
-
名称是从id中获取的,通过指令中scope对象中的行
标签: javascript angularjs