我有一个指令,它使用id
参数来获取控制器作用域中的数组,如果id是静态值,则工作正常,但是如果我使用大括号(例如,我重复指令使用ng-repeat,因此每个id都必须是唯一的,但是如果我使用另一个属性而不是id,它仍然不起作用),那么它不起作用,不会评估大括号,并且查看源代码网络检查员,它实际上是id={{index}}
而不是id=1
。指令属性中的大括号,angularJS
编辑: 我想要做的是当html中有一个堆栈元素时,它会在当前作用域(不是指令的作用域)中创建一个名称与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
(a第二,如果我是卡添加到甲板阵列,那么两个零会改变一个)
以上的作品,因为它不采用NG-重复,属性是硬编码。在属性下面需要动态,并且这不起作用,因为大括号不被评估。
但是,如果我想有使用NG-重复多个甲板它不工作:
<stack ng-repeat="index in range(5)" id="slot{{index}}"></stack>
则ID仍字面意思是“插槽{{指数}}”,而不是“槽0”等。
我可以这样做:
<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)'
,(或者如果它包含括号只能分析)
您在其中一条评论中提到'范围函数返回[“slot1”,“slot2”,...],但在上面的语句中提到它返回一系列数字?那是哪个呢? – ryeballar 2014-09-13 00:24:17
这是数字,但在我的评论中,我说“说范围函数返回...”,因为该评论更加方便。 – 2014-09-13 01:15:42
嗯,让我直接得到这个,你希望'scope.cards'作为'range()'函数的返回数组的引用,而你希望'scope.name'是该数组的项目? – ryeballar 2014-09-13 01:28:50