问题描述
为 $间隔
的AngularJS文档提供了一个控制器使用 $间隔
的一个实例来管理一个计时器,用户可以在视图中玩。您可以阅读。
The AngularJS documentation for $interval
gives an example of using $interval
in a controller to manage a timer that the user can play with in a view. You can read the code for the official example at the angularJS documentation page by clicking n this link.
我试图从这个例子控制器code搬回到一个服务,以便code可以更加模块化。但应用程序不连接服务的看法。我已经重新在,你可以用它来诊断并找出解决问题的办法。 因此需要将code至作出什么具体的变化上面允许用户通过视图中的服务进行交互?
All of the above code is assembled in "working" form in this plnkr that you can use to diagnose and identify the solution to the problem. So what specific changes need to be made to the code above to allow the user to interact with the service through the view?
推荐答案
首先,你没有注入$时间间隔为 mytimer
服务,并尝试使用它
First, you didn't inject the $interval to the mytimer
service and did try to use it.
其次,你必须在 mytimer
服务范围的问题:
secondly, you had scope issues in the mytimer
service:
stop = $interval(function() {
if (this.blood_1 > 0 && this.blood_2 > 0) {
this.blood_1 = $this.blood_1 - 3;
this.blood_2 = $this.blood_2 - 4;
} else {
this.stopFight();
}
}, 100);
声明要创建一个新的作用域函数时,意味着
这
指向一个新的范围。您可以使用绑定
或使用在第5行声明的 $这种
变量(在ES2015你可以简单地请使用箭头功能)。
when declaring a function you are creating a new scope, meaning the this
is pointing to a new scope. you can either use bind
or to use the $this
variable you declared in line 5. (in ES2015 you could simply use the arrow function).
你也中声明的模块exampleController两次 app.js
和 mytimer.js
。
also you declared the module exampleController twice in app.js
and in mytimer.js
.
看看这个工作Plunker:结果
http://plnkr.co/edit/34rlsjzH5KWaobiungYI?p=$p$pview
Take a look at this working Plunker:
http://plnkr.co/edit/34rlsjzH5KWaobiungYI?p=preview
这篇关于我怎么这个区间服务连接到一个看法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!