问题
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