0

I am learning AngularJs. I have a simple controller:

angular.module('test').controller('RouteFinderController', function ($scope) {
    $scope.startSystem = { systemName: "Test" }
});

this works as intended - the view can make use of the startSystem field.

However, if I make a slight change:

angular.module('test').controller('RouteFinderController', function ($scope) {
    setTimeout(function() {
        $scope.startSystem = { systemName: "Test" }
    },0);
});

It no longer works! I can't access the startSystem field anymore.

Why is this, and how do I fix it?

1
  • 1
    Use built-in Angular services, like $timeout (docs.angularjs.org/api/ng/service/$timeout) instead of setTimeout - otherwise Angular doesn't know the scope changed and that it needs to update the view Commented Oct 7, 2014 at 16:20

2 Answers 2

2

This Should answer your question, you have to use $scope.$apply() if you're using setTimeout() but as seen here, using $timeout() is recommended.

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

1 Comment

Great, thanks. I didn't know that $scope.$apply() was required. the setTimeout in my question was just the simpler form of my real problem, which came up when I was trying to load JSON data asynchronously.
1

AngularJS is not aware of the change you made. To apply them you could use

angular.module('test').controller('RouteFinderController', function ($scope) {
    setTimeout(function() {
        $scope.startSystem = { systemName: "Test" }
    },0);
    $scope.$apply();
});

But as $timeout already does that for you, it is much easier to simply use it instead:

angular.module('test').controller('RouteFinderController', function ($scope, $timeout) {
    $timeout(function() {
        $scope.startSystem = { systemName: "Test" }
    },0);
});

Comments

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.