我有一个指令,它使用 id
参数在 Controller 的范围内获取一个数组,如果 id 是静态值,它工作正常,但是如果我使用大括号(例如我重复使用 ng-repeat 的指令,因此每个 id 都需要是唯一的,但如果我使用除 id 之外的另一个属性它仍然不起作用),那么它不起作用,不评估花括号,并查看源代码网络检查器,它实际上是 id={{index}}
而不是 id=1
。
编辑: 我想要做的是当 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
(如果我要在牌组数组中添加一张牌,那么两个零都会变为一)
上面的工作,因为它不使用 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)'
, (或者可能只解析它包含大括号)
最佳答案
请看这里http://jsfiddle.net/4su41a8e/2/
- 用于单向绑定(bind)的花括号
- 双向绑定(bind)没有大括号
HTML:
<div ng-app="app">
<div ng-controller="firstCtrl">
<stack ng-repeat="card in range" item="card" name="{{card.name}}"></stack>
</div>
</div>
指令:
app.directive('stack', function () {
return {
restrict: 'AE',
template: '<h2>cards id: {{cards.id}} </h2><p>name:{{name}}</p>',
scope: {
cards: '=item',
name: '@name',
countOnly: '@'
}
};
});
关于javascript - 指令属性中的花括号,angularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25816596/