0

I can't seem to search the right terms. I've read through a bunch of stuff and cannot find what I want to do. I'm sure there is an angular way of doing this that I haven't read through in the docs.

I want to create a global value or service...something like

main.value 'settings', (->
    data =
        testing: 'teset'

    setTimeout ->
        data.testing = 'what'
        console.log('from settings', data)
    , 5000

    return data
)()

In a real example, the values will be updated with pubsubs instead of a timeout.

I also tried doing this with a factory and a service, but same deal.

My controller might look something like this

main.controller('somecontroller', ['$scope', 'settings',
($scope, settings)->

    $scope.test = settings.testing

    $scope.$watch settings.testing, ->
        console.log 'here we ', settings
        $scope.test = settings.testing

I want to be able to use a dynamically changing global model to update views with controllers.

What is the correct approach with Angular?

1 Answer 1

4

Your main problem here is that you are using the standard browser setTimeout function, which runs out of angular entirely - so angular never picks up that your code modified that value and never triggers a digest cycle.

Best option is to use the $timeout service instead of setTimeout in your example. Alternately, you can use $scope.$apply() within your timeout function to force angular to trigger a digest cycle and update your display.

Additionally, in Angular, there exists a $rootScope object (Access via dependancy injection, just like $scope), which all scopes inherit from. This is the best place to store global variables if that is what you really need to do (however standard advice, as always is to avoid global variables when possible).

2
  • My point in my question was, how can I have a service, have the data returned by the service updated and notify the controllers using it of the update? I don't care about the timeout, it's an example of what I want to do. I don't need to use $rootScope if I can get this working with a service like I want to do. Dec 17, 2014 at 16:15
  • This answers my question stackoverflow.com/questions/19744462/… Dec 17, 2014 at 16:42

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.