我有一個指令,它使用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