Call a controller function from a directive without isolated scope in AngularJS

前端 未结 4 2033
花落未央
花落未央 2020-11-29 16:47

I cannot seem to find a way to call a function on the parent scope from within a directive without using isolated scope. I know that if I use isolated scope I can just use \

4条回答
  •  忘掉有多难
    2020-11-29 17:20

    You want to make use of the $parse service in AngularJS.

    So for your example:

    .directive('confirm', function ($parse) {
        return {
            restrict: 'A',
    
            // Child scope, not isolated
            scope : true,
            link: function (scope, element, attrs) {
                element.bind('click', function (e) {
                    if (confirm(attrs.confirm)) {
                        scope.$apply(function(){
    
                            // $parse returns a getter function to be 
                            // executed against an object
                            var fn = $parse(attrs.confirmAction);
    
                            // In our case, we want to execute the statement in 
                            // confirmAction i.e. 'doIt()' against the scope 
                            // which this directive is bound to, because the 
                            // scope is a child scope, not an isolated scope. 
                            // The prototypical inheritance of scopes will mean 
                            // that it will eventually find a 'doIt' function 
                            // bound against a parent's scope.
                            fn(scope, {$event : e});
                        });
                    }
                });
            }
        };
    });
    

    There is a gotcha to do with setting a property using $parse, but I'll let you cross that bridge when you come to it.

提交回复
热议问题