0

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?

2
  • It seems that you answered by your own question in the last sentence i.e. use a service or put the variable in $rootScope Commented Feb 3, 2016 at 11:52
  • are you asking how to write an angular service? don't use $rootScope for this, that is a fundamental misunderstanding of how $rootScope works. Beyond that, "Global" is never good. Commented Feb 3, 2016 at 11:54

1 Answer 1

2

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

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

4 Comments

And the services (which are injectable) improve testability.
I agree with Hristo. I did have to make a value globally accessible in the same sense as borislemke describes simply because it was seen as being easier to access than injecting a service, disregarding testing. It was accessible from anywhere via $root.
@AdrianMitev I've read somewhere else that it's not a good practice to change a $scope inside a service. What if I had and alert box sitting in my app that needs to change a value whenever an $http request has been done? Lets say, in my code example I need to update $scope.alertTitle after an $http call?
I was hoping to get an explicit answer but after fiddling around a bit I finally understand the concept. Thanks!

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.