【问题标题】:angularjs directive link function not called from compilefunction [closed]未从compilefunction调用angularjs指令链接函数[关闭]
【发布时间】:2014-02-24 08:38:42
【问题描述】:

我想在链接函数中访问 ngModelController。 我正在使用 $compile 根据用户选项动态生成 html。 根据文档,我需要从 compileFunction 返回链接函数。

但是链接函数没有被调用。 Plunker Link

我试图限制用户在 type=number 时输入字母。

编辑

var compileFunction = function (element) {
        return function (scope, telem, tattr, ngModelCtrl) {
            console.log(ngModel);
            var template = helper.getFieldHtml(fieldHtml, scope.options);
            element.html(template);
            $compile(element.contents())(scope);
            return linkFunction.apply(scope, telem, tattr, ngModel);
        };
    };

return {
        scope: { options: '=', ngModel: '=' },
        required: ['ngModel', '^form'],
        restrict: 'E',
        compile: compileFunction
    };

如何在链接函数中访问 ngModelCtrl.. 从编译函数返回

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    你只需要替换“require”而不是“required”

     return {
                scope: { options: '=', ngModel: '=' },
                require: ['ngModel', '^form'],
                restrict: 'E',
                compile: compileFunction
            };
    

    它的工作。

    【讨论】:

    • 哎呀...对不起..非常感谢您指出这一点
    【解决方案2】:

    您的编译函数已经返回一个函数(即链接函数):

    var compileFunction = function (element) {           
        return function (scope) { // linking function
    
    
        };
    };
    

    你可以手动调用你的函数:

    var compileFunction = function (element) {           
        return function (scope) { // linking function
    
           // ...
    
           linkFunction.apply(this, arguments);
        };
    };
    

    【讨论】:

    • 但在这种情况下.. 与链接函数一样.. 将低于参数:链接:函数(范围,元素,属性,ngModel)??
    • @HarishR 是的,感谢.apply(this, arguments);
    【解决方案3】:

    按照你的定义进行

     var compileFunction = function (element) {
            return function (scope) {           //<- This is your link function
                ....
                return (linkFunction);          // not this
            };
        };
    

    另外,我认为范围不能像您使用的那样在编译函数中使用

     var template = helper.getFieldHtml(fieldHtml, scope.options);
     element.html(template);
     $compile(element.contents())(scope);
    

    如果你想在编译函数中调用这三行。

    【讨论】:

    • 我确实得到了范围内控制器传递的值......所以这是可用的......检查 plunker 链接......
    • 是的,这是链接函数调用而不是编译函数。
    • 如何在链接函数中访问 ngModelCtrl,通过编译函数调用...就像使用普通链接函数一样。检查编辑
    猜你喜欢
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 2017-07-13
    • 2014-03-11
    • 1970-01-01
    相关资源
    最近更新 更多