javascript - Why angularJS fails to listen text input when using setInterval() method? -
here code
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> <body ng-app="" style="background:{{val}};" id="body"> <input type="text" ng-model="val" id="color-input"> <input type="button" onclick="render()" value="render"> </body> <script> function render(){ setinterval(function(){mytimer()},5000); } var i=0; function mytimer() { if(i<4){ colors=["red","green","blue","grey"]; document.getelementbyid("color-input").value=colors[i]; i++; } else i=0; } </script>
i using timer of 5sec. when press render button background color of body remains same.
very 1st thing need use angular modularize approach creating angular.module
add components in controller, directive, filters, etc. provide module in ng-app
directive. shouldn't use selectors value of input field, have attached ng-model
field make available value inside controller scope.
you shouldn't use native javascript not work in angular context need replace onclick
ng-click
& setinterval
$interval
lie inside angular controller. using native method outside angular context make problem update binding of angular, because won't run digest cycle. need run digest cycle manually in case, considered bad coding while doing code in angular.
markup
<body ng-app="app" style="background:{{val}};" id="body" ng-controller="mainctrl"> <input type="text" ng-model="val" id="color-input"> <input type="button" ng-click="render()" value="render"> </body>
controller
angular.module('app', []) .controller('mainctrl', function($scope, $interval) { //code here $scope.render = function() { $interval(function() { mytimer() }, 5000); } var = 0; function mytimer() { if (i < 4) { colors = ["red", "green", "blue", "grey"]; $scope.val = colors[i]; i++; } else = 0; } });
Comments
Post a Comment