Javascript 为什么angularJS在使用setInterval()方法时无法侦听文本输入?

Javascript 为什么angularJS在使用setInterval()方法时无法侦听文本输入?,javascript,angularjs,Javascript,Angularjs,这是我的密码 <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"> <inpu

这是我的密码

   <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>

函数render(){
setInterval(函数(){myTimer()},5000);
}
var i=0;
函数myTimer(){

如果(i首先,您需要使用angular模块化方法,创建
angular。模块
添加控制器、指令、过滤器等组件。然后在
ng app
指令中提供该模块。此外,您不应该使用选择器获取输入字段的值,因为您已经附加了
ng模型
t。)o使您可以在控制器范围内使用该值的字段

您不应该使用在angular环境下无法工作的本机javascript,您需要将
onclick
替换为
ng click
&
setInterval
$interval
这一切都将位于angular controller内部。使用来自angular环境外部的本机方法将导致更新ang的绑定出现问题ular,因为它们不会运行摘要循环。在这种情况下,您需要手动运行摘要循环,这被认为是在Angular中执行代码时非常糟糕的编码

标记

<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>

控制器

angular.module('app', [])
.controller('mainCtrl', function($scope, $interval) {
  //code here
  $scope.render = function() {
    $interval(function() {
      myTimer()
    }, 5000);
  }

  var i = 0;

  function myTimer() {
    if (i < 4) {
      colors = ["red", "green", "blue", "grey"];
      $scope.val = colors[i];
      i++;
    } else
      i = 0;
  }
});
angular.module('app',[])
.controller('mainCtrl',函数($scope,$interval){
//代码在这里
$scope.render=function(){
$interval(函数(){
myTimer()
}, 5000);
}
var i=0;
函数myTimer(){
if(i<4){
颜色=[“红色”、“绿色”、“蓝色”、“灰色”];
$scope.val=颜色[i];
i++;
}否则
i=0;
}
});

@PrinzKm很高兴帮助您..谢谢:)