0

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
harishr
  • 17,807
  • 9
  • 78
  • 125

3 Answers3

1

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);
    };
};
Ilan Frumer
  • 32,059
  • 8
  • 70
  • 84
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.

0

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.

Chandermani
  • 42,589
  • 12
  • 85
  • 88
  • i do get the value passed from controller in scope... so that is available.. check the plunker link... – harishr Feb 24 '14 at 10:07
  • Yes that is the link function call not the compile function all. – Chandermani Feb 24 '14 at 10:10
  • how can i access ngModelCtrl in the link function, called through compile function... as i can with normal link function.. check the edit – harishr Feb 24 '14 at 10:20