Search code examples
javascriptangularjsangularjs-scoperootscope

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?


Solution

  • 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