Angular:在Directive中使用“require”来要求父控制器并调用父函数

时间:2017-08-01 11:10:20

标签: javascript angularjs

我在指令中使用require属性来创建2个控制器之间的链接,一切都很好但是当我想从子作用域调用父函数时,我需要使用$ parent.ParentCtl.func的丑陋语法()我想知道我是否可以避免这种语法并调用该函数而不显式编写$ parent表示法。

孩子没有孤立的范围。

我环顾四周,没有找到这个问题的答案。

目前我正在使用工厂将这些功能与父级绑定。

由于

1 个答案:

答案 0 :(得分:0)

好方法

如果您使用的是Angular> = 1.5,则可以将require语法与controllerAs语法结合使用,因此您不必使用范围来访问父级,而是使用对父级的直接引用。当你明确require另一个指令时,由angular创建。例如:

angular.module("test", [])
  .directive("foo", function() {
    return {
      restrict: "E",
      scope: {},
      bindToController: true,
      controllerAs: "fooController",
      controller: function() {
        var controller = this;
        controller.something = "Foo Initial Value";
        controller.setSomething = function(something) {
          controller.something = something;
          console.log("Foo Changed:" + something);
        }
      }
    }
  })
  .directive("bar", function() {
    return {
      scope: {},
      restrict: "E",
      require: {
        "parent": "^^foo"
      },
      controllerAs: "barController",
      template: "Bar <a href='' ng-click='barController.parent.setSomething(\"from template\")'>Change directly on parent</a>",
      bindToController: true,
      controller: function() {
        var controller = this;
        this.$onInit = function() {
          // We can access the parent after the $onInit.
          console.log(controller.parent.something);
        }
      }
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>

<body ng-app="test">
  <foo>
    <bar></bar>
  </foo>
</body>

在此示例中,bar指令需要foo控制器,该控制器将绑定到parent控制器的bar属性。

不那么好的方式

我不喜欢这种方式,因为指令是由于它们以正确的顺序使用而巧合在一起。

angular.module("test", [])
  .directive("foo", function() {
    return {
      restrict: "E",
      scope: true,
      controller: ["$scope", function($scope) {
        $scope.something = "Foo Initial Value";
        $scope.setSomething = function(something) {
          $scope.something = something;
          console.log("Foo Changed:" + something);
        }
      }]
    }
  })
  .directive("bar", function() {
    return {
      scope: true,
      restrict: "E",
      template: "Bar <a href='' ng-click='setSomething(\"from template\")'>Change directly on parent</a> Something: {{something}}"
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>

<body ng-app="test">
  <foo>
    <bar></bar>
  </foo>
</body>

根据我的经验,我建议使用ControllerAs语法。