这是我的 html
<example-directive id="my_id" ng-blur="test()"></example-directive>
这是我的指令
app.directive('exampleDirective', function() {
return {
restrict: 'AE',
scope: {
label: "@",
},
template: '<span class="some_input"> <input required/></span>',
controller: function($scope, $element){
},
link: function(scope, el, attr) {
// this is not responsive when blur out
scope.test = function(){
console.log("what is up");
}
// this is responsive when blur out
el.on('blur', function(){
console.log("this is up");
});
}
}
})
当我
$("#my_id").blur()
仅在控制台中
"this is up"
出现了
我不知道为什么当 example-directive
中发生模糊事件时我无法访问作用域函数
最佳答案
由于您在自定义元素上使用模糊事件,因此它不起作用。您需要在隔离范围内传递该元素,以便该指令可以通过在隔离范围内添加 blur: '&ngBlur'
来访问该方法。其中 blur
变量可以访问指定的 ngBlur
属性函数。
scope: {
label: "@",
blur: '&ngBlur'
},
然后您可以在指令 blur
事件中使用该事件
el.on('blur', function(){
console.log("this is up");
//here we need to run digest cycle manually,
//as we are dealing from outside angular context.
$timeout(function(){ //include `$timeout` dependency in directive
scope.blur();
});
});
关于javascript - 范围函数在使用 Angular 指令链接中不响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33245188/