2014-09-12 67 views
4

我有一个指令,它使用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)',(或者如果它包含括号只能分析)

+0

您在其中一条评论中提到'范围函数返回[“slot1”,“slot2”,...],但在上面的语句中提到它返回一系列数字?那是哪个呢? – ryeballar 2014-09-13 00:24:17

+0

这是数字,但在我的评论中,我说“说范围函数返回...”,因为该评论更加方便。 – 2014-09-13 01:15:42

+0

嗯,让我直接得到这个,你希望'scope.cards'作为'range()'函数的返回数组的引用,而你希望'scope.name'是该数组的项目? – ryeballar 2014-09-13 01:28:50

回答

0

里面的NG-重复使用:

<stack id="index"></stack> 

你不想插值价值,而是对价值的引用。

在指令中,然后使用数据绑定(在该笔记上,您可以使用=或@)将索引绑定到卡变量。您现在可以通过卡片访问链接功能中的实际索引值。

这里有一个包含您的确切问题的代码片段,http://jsbin.com/iMezAFa/2/edit

+0

问题是我需要一种双引用。在我的主控制器中,我有'$ scope.slot1 = [...某些卡片...];'所以在不重复的情况下引用此内容我只是这样做:'',但是在ng - 重复并说范围函数返回'[“slot1”,“slot2”,...]',然后用'','cards'设置为''“slot1” ,当我真的希望它被设置为由控制器范围内的变量称为slot1引用的数组。 – 2014-09-12 21:26:20

6

请看这里http://jsfiddle.net/4su41a8e/2/

  • 花括号单程结合
  • 没有括号为双向绑定

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: '@' 
     } 
    }; 
});