繁体   English   中英

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

[英]Call controller of another directive in 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

使用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 )中设置的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM