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?

Senica Gonzalez
  • 7,996
  • 16
  • 66
  • 108

1 Answers1

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).

Joel Cox
  • 3,289
  • 1
  • 14
  • 31
  • 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. – Senica Gonzalez Dec 17 '14 at 16:15
  • This answers my question http://stackoverflow.com/questions/19744462/update-scope-value-when-service-data-change – Senica Gonzalez Dec 17 '14 at 16:42