2013-10-04 69 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