在AngularJs中调用另一个指令的控制器

时间:2013-03-18 01:16:29

标签: javascript angularjs

如何从同一元素的另一个指令中的$ apply引用指令的控制器函数?示例:

<myelement hint="myelement.controller.getMe()">hoverMe</myelement>

app.directive("myelement", function () {
    return {
        restrict: "E",
        controller: function ($scope) {
            this.getMe = function () {
                return "me";
            };
        }
    }
});

app.directive("hint", function () {
    return {
        restrict: "A",
        controller: function ($rootScope) {
          this.showHint = function (getMsg) {
            alert($rootScope.$apply(getMsg)); //what should be written here?
          }
        },
        link: function (scope, element, attrs, controller) {
            element.bind("mouseenter", function () {
              controller.showHint(attrs.hint);
            });
        }
    }
});

资料来源:http://plnkr.co/edit/9qth9N?p=preview

1 个答案:

答案 0 :(得分:0)

使用require(了解更多信息here)。

app.directive("hint", function () {
  return {
    restrict: "A",
    require: ["myelement", "hint"],
    controller: function ($scope) {
      this.showHint = function (msg) {
        alert($scope.$apply(msg)); //what should be written here?
      }
    },
    link: function (scope, element, attrs, ctrls) {
        var myElementController = ctrls[0],
            hintController = ctrls[1];

        element.bind("mouseenter", function () {
          hintController.showHint(myElementController.getMsg());
        });
    }
  }
});

更新(关于使提示具有通用性,请参阅下面的评论)

要使Hint指令具有通用性,可以使用$ scope作为它们之间的介质。

app.directive("myelement", function () {
 return {
    restrict: "E",
    controller: function ($scope) {
        $scope.getMe = function () {
            return "me";
        };
    }
 }
});
<myelement hint="getMe()">hoverMe</myelement>

唯一的变化是getMe消息未在控制器(this.getMe)中设置,而是在$ scope($scope.getMe)中设置。