Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get AngularJS to compile directive and link function before executing the controller

Due to the nature of my program, I require functions to be placed on the scope and shared between the directive's link function and the controller, like so..

.controller("controller", function($scope, $location, $timeout, model) {

    //irrelevant code

    $scope.addObject(draggables[i]);

};


.directive("designCanvas", function($timeout) {
    return {
        restrict: "A",
        link: function($scope, element) {

            $scope.addObject = function(draggable) {

                // irrelevant code
            }
        }
    }
}

When I make this function call I get '$scope.addObject is not a function'.

My problem is the controller is being executed before angularJS has evaluated the link function, because the function call works fine when I delay it by a few seconds using $timeout

So my question is, how can I get the contents of the link function to compile first?

like image 671
Tom Hadkiss Avatar asked Mar 12 '26 12:03

Tom Hadkiss


1 Answers

I recommend writing this function as a service and inject the service into the directive and controller. Shared function should be implemented as a service.

.factory("objectService",function(){
    return {
       addObject : function (draggable){
          //your code of this function
       }
    };
});

.controller("controller", function($scope, $location, $timeout, model,objectService) {

    //irrelevant code

    $scope.addObject = function (draggable){
        objectService.addObject(draggable); //reuse this function
       //objectService.addObject.call($scope,draggable) if you want to call this function with $scope as the context.
    };
};

.directive("designCanvas", function($timeout,objectService) {
    return {
        restrict: "A",
        link: function($scope, element) {
            $scope.addObject = function(draggable) {
                objectService.addObject(draggable); //reuse this function.
                //objectService.addObject.call($scope,draggable) if you want to call this function with $scope as the context.

                //write more logic specific to this function, like modifying link's local data.
            }
        }
    }
}
like image 113
Khanh TO Avatar answered Mar 15 '26 03:03

Khanh TO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!