0

In the below code I have a variable named $scope.name. By default it has value "Hello 1". After 5 seconds I have set setTimeout function which updates the value of $scope.name to "Hello 2".

The variable shows the change in debug mode. But the new value does not update to {{name}}. In other words it just show the old value "Hello 1" on the page, not "Hello 2" which is required.

Thanks for help in advance.

var quizApp = angular.module("quizApp",[]);
quizApp.controller("quizCtrl",function($scope){

    $scope.name = "Hello 1";

    function pAHL(){
        $scope.name ="hello 2";
    }
    setTimeout(pAHL, 5000)
})

2 Answers 2

2

You don't need to use $timeout.

function pAHL(){
    $scope.name ="hello 2";
    $scope.$apply();
}

EDIT And a more elegant solution which avoids digest errors is to use $timeout:

function pAHL(){
    $timeout(function () {
        $scope.name ="hello 2";
    });
}

Should do the trick. Fiddle

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

2 Comments

if now pAHL gets called from within angular, it will produce digest error. I think $scope.$apply should be used rather in the place, where non-angular event occured, that way you can reuse the same function for angular and non-angular code
@doodeec yeah, what you're saying does make sense. But my solution is based on certain assumptions which hold in this case.
1

change setTimeout(pAHL, 5000) to $timeout(pAHL, 5000) and inject $timeout into quizCtrl

var quizApp = angular.module("quizApp",[]);
quizApp.controller("quizCtrl",function($scope, $timeout){
    $scope.name = "Hello 1";

    function pAHL(){
        $scope.name ="hello 2";
    }
    $timeout(pAHL, 5000)
})

or the second option is to use $scope.$apply()

setTimeout(function() {
    $scope.$apply(pAHL);
}, 5000)

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.