【问题标题】:pass parameters to several AngularJS directive instances?将参数传递给几个 AngularJS 指令实例?
【发布时间】:2013-10-04 04:35:24
【问题描述】:

关于 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>

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    指令的所有实例都使用相同的范围,并且每次调用 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);
          }
        };
      })
    

    【讨论】:

    • scope: { type: '@element' } 会更好
    • 这个答案对我不起作用,我认为它混淆了我的指令(并且没有加载)但话又说回来,我使用的是 ng 1.2
    【解决方案2】:

    在您共享的示例中,指令共享父范围。由于所有指令共享相同的父作用域,因此只有一个变量 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

    【讨论】:

    • 非常感谢。刚刚在 egghead.io 上通过这个,它开始“隔离范围是你可以阅读文档数天的东西之一,然后有人向你展示它,然后你就像'哦,这很容易'” - egghead.io/lessons/angularjs-understanding-isolate-scope
    • scope:true //Creates new scope for each directive instance
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 2014-07-09
    • 2012-11-23
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多