javascript - angularjs 1.5 组件一种方式绑定(bind)不适用于 setInterval

标签 javascript angularjs angular-components

我有一个简单的组件,它使用计时器来增加 View 中的值。我使用 setInterval 来自动递增该值,我还使用按钮来递增该值。单击按钮按预期工作,但 setInterval 什么也不做,没有错误,没有增量。这是代码:

export default angular.module('directives.timer', [])
.component('timer',{

bindings:{
    count: '<'
},
template:`<div>{{$ctrl.count}}</div>
          <div><button ng-click="$ctrl.increment()">increment</button></div>
          <pre>{{$ctrl}}</pre>`,

controller: function(){
   this.count = 0;
   this.tick = function(){
       this.count = this.count++;
   }
   this.increment = function(){
       this.count++;
   }

   this.$onInit = function(){
       var _this = this;
       setInterval(function(){
           _this.tick();
       }, 1000);
   }
}
}).name

tick 函数被调用,值增加,但 UI 没有更新。 怎么了?谢谢

最佳答案

Angular 并不知道发生了变化,因为你正在改变 Angular 范围之外的值。而是使用 Angulars 包装器 $interval。

Docs :

AngularJS's wrapper for window.setInterval. The fn function is executed every delay milliseconds.

关于javascript - angularjs 1.5 组件一种方式绑定(bind)不适用于 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42880367/

相关文章:

angular - Angular 5 中同一页面中的多个组件

javascript - 如何有一个不在滚动对象旁边的滚动条?

javascript - JQueryUI 可排序 : Allow sorting only to second list but not back to first

javascript - 提交表单前的jquery

javascript - 通过 AJAX 加载整个 AngularJS 页面

javascript - Angular : How can I avoid tightly coupling stacked directives when both need values from parent scope?

arrays - 在 angularfire 1.0.0 中通过唯一的 firebase id 获取项目

forms - 子组件的 Angular Form 验证

angular - 如何使用服务的输入/输出动态创建组件实例并将其分别注入(inject) DOM?

php - jquery如何获取点击的div的id