borislemke
borislemke

Reputation: 9136

Make an Object global in AngularJS

In plain javascript, I can group similar functions into an object like so:

var Monolog = {

  notify: function(title, message) {

      // Do something with title and message
    },

  confirm: function(title, message, func) {

      // Do something with title, message and func
    }
}

Which I can access like so:

Monolog.notify('Error', 'Error message');

Now, using AngularJS, I need the functions inside Monolog to change a $scope.variable, which mean that I would either have to use service or the rootScope.

How would I do this?

Upvotes: 0

Views: 63

Answers (1)

Hristo Enev
Hristo Enev

Reputation: 2541

Service is the better choice. You should try to use services over the $rootScope because they make the code more reusable and readable. Also using the global scope is bad idea in most cases.

Changing your $scope.variable can be accomplished by a setter and a getter in a service.

EDIT

And also as @Adrian added:

Services (which are injectable) improve testability

Upvotes: 2

Related Questions