如何在同一元素的另一个指令中引用来自$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
发布于 2013-03-18 09:24:00
使用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());
});
}
}
});更新(关于使提示通用,请参阅下面的评论)
要使提示指令通用,您可以使用$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)中设置的。
https://stackoverflow.com/questions/15468350
复制相似问题