2015-06-10 40 views
2

我有$scope中的數據,根據classNames的計數範圍,我需要在頁面中創建具有scope的不同數據的元素。怎麼樣?如何使用不同的數據創建多個`directive`實例

我想添加更多no.of directive元素,但我只看到一個輸出。並且我無法將$scope數據傳遞給它。

這樣做的正確方法是什麼?

這裏是我的嘗試:

<div class="wrapper" ng-app="myApp"> 
    <div class="helloWorld" ng-controller="hello"> 
     <ul> 
      <li ng-repeat="item in items"> 
       {{item.name}} 
      </li> 
     </ul> 
     <hello-world/> //added multiple times 
     <hello-world/> 
     <hello-world/> 
     <hello-world/> 
     <hello-world/> 
    </div> 

</div> 

var app = angular.module('myApp', []); 

app.controller('hello', function ($scope) { 
    $scope.items = [ 
     {name:'name1', className:'green'}, 
     {name:'name2', className:'blue'}, 
     {name:'name3', className:'brown'}, 
     {name:'name4', className:'yellow'}, 
     {name:'name5', className:'red'} 
    ]; 
}); 

app.directive('helloWorld', function() { 
     return { 
      restrict: 'AE', 
      replace: 'true', 
      template: '<h3 class="{item.className}">Hello World!! from color of {{item.className}}</h3>', 
      scope: { 
       className: '@' 
      }, 
      link : function ($scope, elem, attr) { 
      } 
     } 
}); 

jsfiddle

任何一個能幫助我理解這個概念,並在此創建指令的多個實例?

在此先感謝。

回答

1

問題是您沒有正確關閉指令。根據定義,Tag指令不能自行關閉。因此,當您編寫<hello-world />時,會發生什麼情況是標記保持未關閉狀態,並且後續指令無法解析。

它應該是:

<hello-world></hello-world> 
<hello-world></hello-world> 
<hello-world></hello-world> 
<hello-world></hello-world> 
<hello-world></hello-world> 

演示:http://jsfiddle.net/ydkezd15/2/

+0

好,如何映射顏色名稱相應的 – 3gwebtrain

+0

你想循環遍歷'hello-world'多次,並將顏色綁定到它們中的每一個? – dfsq

+0

是的,確切地說。以及我想爲每個添加不同的值。每個需要添加一個點擊事件。 – 3gwebtrain

4

..我正在試圖增加更多的節數指令元素,但我只看到一個 輸出。

首先,您需要正確關閉指令標記。使用 所以<hello-world><hello-world/>而不是<hello-world/>。另外,將指令放在ng-repeat中以獲取多個元素。

 <li ng-repeat="item in items"> 
      {{item.name}} 
      <hello-world class-name="{{item.className}}"></hello-world> 
     </li> 

,我不能夠在$範圍的數據傳遞給它。

這是因爲您已爲您的指令創建了「隔離範圍」!

scope: { 
     className: '@' 
     } 

@跡象表明,在孤立的範圍className將從屬性class-name在指令

app.directive('helloWorld', function() { 
    return { 
     restrict: 'E', 
     replace: 'true', 
     template: '<h3>Hello World!! from color of "{{className}}"</h3>', 
     scope: { 
      className: '@' 
     }, 
     link: function ($scope, elem, attr) {} 
    } 
}) 

這裏得到它的價值是在dmeo

+0

一般如何從角度獲取url中的數據。在每個「控制器」可能需要不同的URL和數據的情況下(如果有的話)如何在每個控制器上添加獲取過程。或者需要我們根據控制器的「參數」提供服務來提供數據 - 您能否展示一種方法來執行此操作? - 對於附加問題,我非常抱歉 – 3gwebtrain

+0

不符合要求。需要一些代碼才能更好地理解。如何爲此發佈單獨的問題? ;) – nalinc

+1

當然,會爲你做 – 3gwebtrain

相關問題