0

如何在同一元素的另一个指令中从 $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

4

1 回答 1

0

使用 require (在此处阅读更多信息)。

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) 中。

于 2013-03-18T01:24:00.390 回答