有没有办法在使用指令包装数据时不丢失与当前 Controller 的连接?
我的问题是,包装模板中的指令不再连接到外部 Controller ,因此我无法执行该函数。
包装指令:
myApp.directive('wrapContent', function() {
return {
restrict: "E",
scope: {
model: "=",
datas: "="
},
templateUrl: "./any/template.php",
link: function(scope, element, attr) {
// any
}
};
});
包装模板中的指令
myApp.directive('doAction', function() {
return {
restrict: "A",
link: function(scope, elem, attrs) {
$(elem).click(function(e) {
scope.$apply(attrs.doAction);
});
}
}
});
Controller :
lmsApp.controller('OutsideController', function ($scope){
$sope.sayHello = function() {
alert("hello");
};
});
我要执行函数的 HTML (template.php):
<div>
<do-action="sayHello()"></do-action>
</div>
我如何调用外部的 wrapContent
指令(已更新):
<div ng-controller="OutsideController">
<wrap-content model="any" datas="data_any"></wrap-content>
</div>
如何执行 sayHello()
函数?
感谢您的帮助!我将不胜感激。
最佳答案
wrapContent 指令将在 Controller 范围内处理。 DoAction 指令将与 wrapContent 指令的 isolateScope 一起处理。
解决方案 1: 使用“&”在 wrapContent 中获取对 sayHello 函数的引用,并在事件处理程序中执行它。
解决方案 2: 不要在事件处理程序中使用范围,而是使用 scope.$parent。
关于javascript - AngularJS - 指令包装而不丢失与 Controller 的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28660428/