angularjs directive link function not called from compilefunction [closed]

情到浓时终转凉″ 提交于 2019-12-13 04:27:07

问题


I want to access the ngModelController in the linking function. I am using $compile to generate the html dynamically based on the user options. as per the docs I need to return the linking function from compileFunction.

but the linking function is not getting called. Plunker Link

I am trying to restrict user from entering alphabets when type=number.

EDIT

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
    };

how to I access ngModelCtrl in the link function.. returned from compile function


回答1:


You just need to replace "require" instead of "required"

i.e.

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

it's work.




回答2:


Your compile function already returns a function (that is the linking function):

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


    };
};

You can manually invoke your function:

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

       // ...

       linkFunction.apply(this, arguments);
    };
};



回答3:


Going by your definition

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

Also i don't think the scope is available to use in compile function as you are using like

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

in case you want to call these three lines in compile function.



来源:https://stackoverflow.com/questions/21982656/angularjs-directive-link-function-not-called-from-compilefunction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!