0

I have a function attached to my $rootScope

myApp.run(['$rootScope','$location', function($rootScope,$location){

    $rootScope.myFunction = function(){
     //do something
    };

}]);

I need to move myFunction to angular.constant. How do I do that?

1 Answer 1

1

By just registering it as a constant, using angular.constant(name, function):

angular.module('example', []);

angular.module('example')
    .constant('myFunction', myFunction);

function myFunction() {
  return 'foobar';
}

angular.module('example')
    .controller('ExampleController', ['myFunction', ExampleController]);

function ExampleController(myFunction) {
  this.text = myFunction();
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="example">
  <div ng-controller="ExampleController as vm">{{vm.text}}</div>
</div>

However, while you can register anything as a constant (functions, objects...), note that its purpose is to save few application wide constants like the host-domain. For actual business logic, I would always recommend to use angular.service, to group functionality into meaningful modules.

Sign up to request clarification or add additional context in comments.

3 Comments

Wonderful, works perfectly. But if i have 3 constant functions i will inject my controller with 3 functions (myFunc1,MyFunc2...). And also how to do i add $location in MyFunction() in the example you gave. I am a new to AngularJS so sorry if my questions sound too newbie.
@user3052526 You should create a angular.service instead, put your functions in it and inject the service where you need it. You can inject $location like anything else, using the array syntax I used i the example above injecting myFunction
Oh cool, so the service becomes the constant nice. Thanks @LionC

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.