首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在AngularJs中调用另一个指令的控制器

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

Stack Overflow用户
提问于 2013-03-18 09:16:29
回答 1查看 943关注 0票数 0

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

代码语言:javascript
运行
复制
<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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-18 09:24:00

使用require (阅读更多关于它的here)。

代码语言:javascript
运行
复制
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());
        });
    }
  }
});

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

要使提示指令通用,您可以使用$scope作为它们之间的媒介。

代码语言:javascript
运行
复制
app.directive("myelement", function () {
 return {
    restrict: "E",
    controller: function ($scope) {
        $scope.getMe = function () {
            return "me";
        };
    }
 }
});
代码语言:javascript
运行
复制
<myelement hint="getMe()">hoverMe</myelement>

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15468350

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档