Refresh html when model changes

I have a controller like this:

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

Side:

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

I want the text box to automatically update the value when model.title changes (every 1 second). Please tell me if possible

+4
source share
4 answers

Model changes that apply outside of some Context observed with AngularJS should be wrapped in a scope. $ apply (function () {...});

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

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

Use $ timeout , which wraps your function inside a try / catch block to handle exceptions correctly and does $ scope.apply (); for you, and this is easier to check than regular window.setInterval:

 function postCtrl($scope, $timeout){ $scope.model = { title: 'one' }; $timeout(function(){ $scope.model += ' more one,'; }, 1000); } 
+5
source

You just need to call $scope.$apply or wrap it around the destination of $scope.model .

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

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

0
source

If you are open to using additional libraries, KnockoutJS does the same. You bind the model and whenever the model is updated, the corresponding HTML is updated.

-4
source

Source: https://habr.com/ru/post/1479413/


All Articles