karaxuna
karaxuna

Reputation: 26940

Update html on model change

I have such controller:

function postCtrl($scope){
    $scope.model = { title: 'one' };

    window.setInterval(function(){
        $scope.model += ' more one,';
    }, 1000);
}

View side:

<div ng-controller="postCtrl">
     <input type="text" ng-model="model.title"/>
</div>

I want textbox to automatically refresh value when model.title changes (every 1 second). Please tell me if it's possible

Upvotes: 4

Views: 369

Answers (4)

kfis
kfis

Reputation: 4729

Model changes, that are applied outside of some AngularJS-observed Context, should be wrapped into scope.$apply(function(){...});

http://docs.angularjs.org/api/ng.$rootScope.Scope

window.setInterval(function(){
    $scope.$apply(function(){
       $scope.model += ' more one,';
    });
}, 1000);

Upvotes: 3

Aleksander Blomsk&#248;ld
Aleksander Blomsk&#248;ld

Reputation: 18552

Use $timeout which wraps your function inside a try/catch-block for proper exception handling, and executes a $scope.apply(); for you, and is way easier to test than normal window.setInterval:

function postCtrl($scope, $timeout){
    $scope.model = { title: 'one' };

    $timeout(function(){
        $scope.model += ' more one,';
    }, 1000);
}

Upvotes: 5

Langdon
Langdon

Reputation: 20073

You just need to call $scope.$apply or wrap it around your $scope.model assignment.

function postCtrl($scope){
    $scope.model = { title: 'one' };

    window.setInterval(function(){
        $scope.model.title += ', 1';
        $scope.$apply();
    }, 1000);
}

Example: http://jsfiddle.net/qeD6Q/

Upvotes: 0

sriniris
sriniris

Reputation: 133

If you're open to using additional libraries, KnockoutJS does the exact same thing. You bind a model and whenever the model is updated, the corresponding HTML gets refreshed.

Upvotes: -4

Related Questions