【问题标题】:angularjs 1.5 component one way binding not working with setIntervalangularjs 1.5组件单向绑定不适用于setInterval
【发布时间】:2017-08-10 08:38:00
【问题描述】:

我有一个简单的组件,它使用计时器来增加视图中的值。我使用 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 没有更新。 怎么了?谢谢

【问题讨论】:

  • 我认为这与单向绑定没有任何关系。您可以将绑定更改为 {},这仍然有效。您的控制器所做的第一件事就是手动将 count 的本地属性设置为 0。

标签: javascript angularjs angular-components


【解决方案1】:

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

Docs

AngularJS 的 window.setInterval 包装器。 fn 函数是 每延迟毫秒执行一次。

【讨论】:

  • 没错,$interval 服务是一个包装器,然后触发摘要循环。
猜你喜欢
  • 2016-10-04
  • 2016-12-24
  • 2017-05-10
  • 1970-01-01
  • 2016-12-12
  • 2017-06-17
  • 2016-07-21
  • 1970-01-01
  • 2018-01-03
相关资源
最近更新 更多