2013-03-20 6 views
15

にアクセスすることはできません、私はは、だから、プロパティ

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

     } 
    }); 

以下の比較的単純なAngularjsディレクティブを持っており、ここで私は

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

HTML

にディレクティブを呼ぶところであります各 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が作成するスコープをディレクティブに使用させることができます。 –

答えて

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>