Senica Gonzalez
Senica Gonzalez

Reputation: 8212

angular global value that dynamically changes

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?

Upvotes: 0

Views: 306

Answers (1)

Joel Cox
Joel Cox

Reputation: 3469

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

Upvotes: 4

Related Questions