2013-03-20 63 views
15

所以,我比较简单Angularjs指令以下在angularjs指令范围暴露的对象,不能访问性能

app.directive('myDirective', function() { 
     return { 
      restrict: 'E', 
      scope: { 
       site: '@', 
       index: '@' 
      }, 
      template: '<div>{{site}}</div>', 
      replace: true, 

     } 
    }); 

而且这里是我称之为HTML

<div id="eventGraphic" class="span12"> 
    <my-directive ng-repeat="site in IEvent.sites" site="{{site}}" index="{{$index}}"></my-directive> 
</div> 

指令其中,由于每个site是一个对象,产生此输出(从浏览器复制)

{"name":"Hurlburt","_id":"5148bb6b79353be406000005","enclaves":[]} 
{"name":"Walker Center","_id":"5148cca5436905781a000005","enclaves":[]} 
{"name":"test1","_id":"5148ce94436905781a000006","enclaves":[]} 
{"name":"JDIF","_id":"5148cf37436905781a000007","enclaves":[]} 

但是,如果我将指令中的模板更改为

template: '<div>{{site.name}}</div>', 

它不会产生任何输出。这似乎是一个相当简单的用例,任何想法我可能做错了什么?期望的输出将只是每个对象中的name字段。

+0

是您的指令将允许用户更改了'site'数据,或它会在范围上创建自己的属性吗?如果不是,那么你可能不需要隔离作用域 - 你可以保存一些内存并让指令使用ng-repeat创建的作用域。 – 2013-03-20 22:26:43

回答

21

您需要使用'='来映射对象。 '@'意味着你只是将一个字符串值传递给新的作用域。

app.directive('myDirective', function() { 
     return { 
      restrict: 'E', 
      scope: { 
       site: '=', //two-way binding 
       index: '@' //just passing an attribute as a string. 
      }, 
      template: '<div>{{site}}</div>', 
      replace: true, 

     } 
    }); 
在您的标记

那么不要使用该属性的绑定,你只需要把这个表达式:

<div id="eventGraphic" class="span12"> 
    <!-- below, site="site" is passing the expression (site) to 
     the two way binding for your directive's scope, 
     whereas index="{{$index}}" is actually evaluating the expression 
     ($index) and passing it as a string to the index attribute, 
     which is being put directly into the directive's scope as a string --> 
    <my-directive ng-repeat="site in IEvent.sites" 
      site="site" 
      index="{{$index}}"></my-directive> 
</div>