2013-03-20 64 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>