javascript - two way databinding in angular not working as I expected -


i'm trying test simple databinding concept after going thru angular documentation.

this sample html file

<body ng-app>   <h1>hello, world!</h1>   <div ng-controller="ctrl">     <input type="text" ng-model="count" />     count: <span ng-bind="count"></span>   </div> </body> 

and ctrl function

var = 0; function ctrl($scope) {   $scope.count = i;   inc(); }  function inc() {   i++;   settimeout(inc, 1000); } 

i expecting count in html keep updating var incremented every sec in javascript.

but doesn't work way.

i'm trying find wrong code , example demo concept of 2 way databinding (meaning when javascript object changed should reflected in html)

two problems:

  1. $scope.count = i; not reference global i , thus, regardless of next problem, not update (this not angular problem).

  2. your interval function update counter without angular noticing it. overcome problem use $apply or special angular helpers, e.g. $timeout

a working example be:

(function (app, ng) {   'use strict';    app.controller('ctrl', ['$scope', '$timeout', function ($scope, $timeout) {     $scope.count = 0;      (function _update() {       $scope.$apply(function () {         $scope.count += 1;       });        $timeout(_update, 1000);     }());   }]); }(angular.module('app', []), angular)); 

demo: http://jsbin.com/unasaf/1/


or less complicated version be:

function ctrl($scope, $timeout) {   $scope.count = 0;    $scope.increment = function increment() {     $scope.count += 1;   };    (function _update() {     $scope.increment();         $timeout(_update, 1000);   }()); } 

Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -