2013-10-04 70 views
2

對angularJS的新手問題,但沒有看到類似的案例在教程搜索。將參數傳遞給幾個AngularJS指令實例?

如何使用相同的指令定義將不同的參數傳遞給單獨的div實例?這裏我期望看到red green blue,但我在HTML中看到blue blue blue。我看到控制器在鏈接之前被調用。

http://jsfiddle.net/gradualstudent/Y2bBy/

<!DOCTYPE html> 
<html > 
<head> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script> 
    <script> 
     var app = angular.module('myApp', []); 

     app.directive("element", function() { 
     return { 
      restrict: "A", 
      template: '<h1>{{type}}</h1>', 
      link: function (scope, element, attrs) { 
      scope.type = attrs.element; 
      console.log("Setting: "+scope.type); 
      }, 
      controller: function ($scope) { 
      console.log("Checking: "+$scope.type); 
      } 
     }; 
     }) 

    </script> 
</head> 
<body ng-app="myApp"> 
    <div element="red">1</div> 
    <div element="green">2</div> 
    <div element="blue">3</div> 

</body> 
</html> 

回答

5

你的指令的所有實例使用相同的範圍和每次link函數被調用時,它會覆蓋先前設定的scope.type。如果你創建一個孤立的範圍那麼它會工作,因爲該指令的每個實例都將獲得自己的範圍:

app.directive("element", function() { 
    return { 
     restrict: "A", 
     scope: {}, 
     template: '<h1>{{type}}</h1>', 
     link: function (scope, element, attrs) { 
     scope.type = attrs.element; 
     console.log("Setting: "+scope.type); 
     }, 
     controller: function ($scope) { 
     console.log("Checking: "+$scope.type); 
     } 
    }; 
    }) 
+0

範圍:{類型:「@元素'}會更好 –

+0

這個答案不適合我,我認爲它混淆了我的指令(並沒有加載),但是,然後再次,我使用ng 1.2 – Worthy7

5

在已共享的例子中,指令共享父範圍。由於所有指令共享相同的父範圍,因此只有一個變量type可用。

,你必須的選項是做任何

scope:true //Creates new scope for each directive instance 

scope:{} //as provided by akonsu. Creates an isolated scope. 

只是爲了完整性,請花時間理解範圍原型繼承https://github.com/angular/angular.js/wiki/Understanding-Scopes

+0

非常感謝。剛剛通過egghead.io得到了這個結果,它開始「隔離範圍是可以在幾天內閱讀文檔的東西之一,然後有人向你展示它,然後你就像'哦,那很容易'」 - http://egghead.io/lessons/angularjs-understanding-isolate-scope – prototype

+0

'scope:true //爲每個指令實例創建新的作用域 – Worthy7