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?
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.
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With