Javascript AngularJS-覆盖指令';s编译函数不';调用链接函数?
我通过重写指令的compile来定制指令模板,但它在运行compile函数后不会调用link函数Javascript AngularJS-覆盖指令';s编译函数不';调用链接函数?,javascript,angularjs,Javascript,Angularjs,我通过重写指令的compile来定制指令模板,但它在运行compile函数后不会调用link函数 angular.module('app').directive('ngValidate', ['$compile', function($compile){ return { restrict: 'A', require: '?ngModel', compile:function($element, $attrs, linker){ // this run
angular.module('app').directive('ngValidate', ['$compile', function($compile){
return {
restrict: 'A',
require: '?ngModel',
compile:function($element, $attrs, linker){
// this run
console.log('compile>>>');
// append error message
$element.append('<div></div>');
$element.bind('blur',function(){
console.log('onblur');
});
$compile($element.contents());
},
controller: function($scope, $element, $attrs){
// this run
console.log('controller>>>');
},
link: function($scope, $element, $attrs, ctrl) {
// this doesn't run
console.log('link>>>');
}
}
}]);
angular.module('app')。指令('ngValidate',['$compile',函数($compile){
返回{
限制:“A”,
要求:“?ngModel”,
编译:函数($element、$attrs、linker){
//这次跑步
log('compile>>>');
//附加错误消息
$element.append(“”);
$element.bind('blur',function(){
console.log('onblur');
});
$compile($element.contents());
},
控制器:函数($scope、$element、$attrs){
//这次跑步
console.log('controller>>');
},
链接:函数($scope、$element、$attrs、ctrl){
//这个不能运行
log('link>>>');
}
}
}]);
编译后我需要运行link的原因是我想访问范围,可以从compile访问范围?如注释中所述,如果您有编译函数,它应该返回link函数,而不是在指令定义对象上单独定义它
angular.module('app', []).directive('ngValidate', ['$compile', function($compile){
return {
restrict: 'E',
require: '?ngModel',
compile:function($element, $attrs, linker){
// this run
console.log('compile>>>');
// append error message
$element.append('<div></div>');
$element.bind('blur',function(){
console.log('onblur');
});
$compile($element.contents());
return function($scope, $element, $attrs, ctrl) {
// this doesn't run
console.log('link>>>');
}
},
controller: function($scope, $element, $attrs){
// this run
console.log('controller>>>');
}
}
}]);
angular.module('app',[])。指令('ngValidate',['$compile',函数($compile){
返回{
限制:'E',
要求:“?ngModel”,
编译:函数($element、$attrs、linker){
//这次跑步
log('compile>>>');
//附加错误消息
$element.append(“”);
$element.bind('blur',function(){
console.log('onblur');
});
$compile($element.contents());
返回函数($scope、$element、$attrs、ctrl){
//这个不能运行
log('link>>>');
}
},
控制器:函数($scope、$element、$attrs){
//这次跑步
console.log('controller>>');
}
}
}]);
请参阅文档中关于链接属性的详细说明:“仅当未定义compile属性时才使用此属性。”