我正在研究 ng-blur 的自定义实现之一(我知道它现在已经在标准 AngularJS 中可用)。最后一行我不明白。
.controller('formController', function($scope){
$scope.formData = {};
$scope.myFunc = function(){
alert('mew');
console.log(arguments.length);
}
})
.directive('mew', function($parse){
return function(scope, element, attr){
var fn = $parse(attr['mew']);
element.bind('blur', function(event){
scope.$apply(function(){
fn(scope);
});
});
}
});
在 View 中,有一个简单的 mew="myFunc()"
应用于输入。
我的问题是为什么我们要在指令的最后一行将作用域传递给函数。我试图让它在没有它的情况下工作,但它没有。到底发生了什么?
这也有效scope.$apply(attr.mew)
。相同的原因还是不同的原因?
最佳答案
$parse
只做就是这样,它解析传入的字符串,您需要使用当前范围调用结果函数,否则它怎么知道哪个要调用的函数?
scope.$apply
按以下方式工作:
- The expression is executed using the
$eval()
method.- Any exceptions from the execution of the expression are forwarded to the
$exceptionHandler
service.- The watch listeners are fired immediately after the expression was executed using the
$digest()
method.
之所以 scope.$apply(attr.mew)
是因为它正在执行上述所有操作。它正在解析,然后将解析结果应用到作用域。
另一种选择是使用隔离范围将指令绑定(bind)到 mew
属性。
return {
scope: {
mew: '&'
},
link: function (scope, element, attr) {
var fn = scope.mew;
element.bind('blur', function (event) {
scope.$apply(function () {
fn();
});
});
}
}
关于javascript - 谁能解释一下这段小代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24540505/