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:
$scope.count = i;
not reference globali
, thus, regardless of next problem, not update (this not angular problem).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
Post a Comment