How to call a function on a directive scope from the controller

前端 未结 2 1415
感动是毒
感动是毒 2021-01-15 13:20

I\'ve searched all over the internet and cannot find a solution please help!

directive(\'menu\',function(){
    return{
        link : function(scope,element         


        
相关标签:
2条回答
  • 2021-01-15 14:01

    Delay the call to foo() using $evalAsync():

    controller : function($scope){
        $scope.$evalAsync(function() {
            $scope.foo();
            console.log($scope);
        });
    }
    

    fiddle

    You could also use $timeout() instead of $evalAsync(). Both allow the link function to execute first.

    0 讨论(0)
  • 2021-01-15 14:12

    As Ye Liu said, your controller calls your directive's compile and then link functions. From the angular directive doc (http://docs.angularjs.org/guide/directive):

    The controller is instantiated before the pre-linking phase

    The controller will be within the scope of your app, and once the post-link function finishes, your directive will be a child of this scope. Consider that the link function's purpose is to bind model data to your template and set watches for bound variables, not to create a discreet 'directive object'.

    If you are trying to set the foo function inside of the link function in order to access directive scope variables, take a look at directive delegate functions and bound variables in the "scope:" directive attribute. The angular directive tutorial gives a somewhat obtuse version of this as its final example ("zippy"), and Angularjs Directive Delegate not firing through intermediary handler gives an example of a delegate function you can invoke from your template itself.

    0 讨论(0)
提交回复
热议问题