javascript - AngularJS - 指令包装而不丢失与 Controller 的连接

标签 javascript angularjs angularjs-directive controller directive

有没有办法在使用指令包装数据时不丢失与当前 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/

相关文章:

javascript - 将单选按钮输入添加到文本框输入并将其存储在列表中?

java - 解析从js发送到Java的json字符串时出错

如果未通过异常身份验证,AngularJS 会重定向到登录页面

angularjs - 单选按钮指令不绑定(bind) ngModel

angularjs - 我可以在 Angular 指令的属性值中使用双引号吗?

Javascript 对象作为 Angular 指令属性中的函数参数

javascript - 在 ASP MVC 5 中使用 AJAX 时,HttpPostedFileBase 为空

javascript - CSS 从中心过渡到右下角

javascript - 表单验证中的错误消息未按预期显示

javascript - 替换 "templateUrl":path with "template":content for angular directives using gulp