简体   繁体   中英

Can anyone explain this small piece of code?

I was looking at one of the custom implementations of ng-blur (I know it's already available in the standard AngularJS now). The last line is what I don't understand.

.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);
            });
        });
    }
});

In the view there's a simple mew="myFunc()" applied to inputs.

My question is why are we passing the scope to the function in the very last line of the directive. I tried to make it work without that but it doesn't. What's actually happening?

Also this too works scope.$apply(attr.mew) . Same reason or something different?

$parse only does just that , it parses the string passed in, you need to call the resulting function with the current scope because otherwise how else would it know which function to call?

scope.$apply works in the following manner:

  1. The expression is executed using the $eval() method.
  2. Any exceptions from the execution of the expression are forwarded to the $exceptionHandler service.
  3. The watch listeners are fired immediately after the expression was executed using the $digest() method.

The reason scope.$apply(attr.mew) is due to the fact that it's doing all of the above. It is parsing, and then applying the result of the parse to the scope.

Another option is to use an isolate scope to bind your directive to the mew attr.

   return {
        scope: {
            mew: '&'
        },
        link: function (scope, element, attr) {
            var fn = scope.mew;
            element.bind('blur', function (event) {
                scope.$apply(function () {
                    fn();
                });
            });
        }
    }

Example

For this specific example it will work, but as you said, the blur is out of the digest loop. In most of the use cases the function will change data on one scope or another, and the digest loop should run and catch those changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM