the*_*ino 6 javascript timeout angularjs
我有一个让我非常疯狂的AngularJS问题.我有一个看起来像这样的服务(这是一个说明问题的例子)
var app = angular.module('test-module');
app.service('ToolService', function($timeout){
this.doSomething = function() {
console.log("y u no referenced as method?!?");
}
this.runTimeoutExample = function(){
$timeout(function(){
this.doSomething();
}, 1000);
}
})
Run Code Online (Sandbox Code Playgroud)
我的控制器看起来像这样:
var app = angular.module('test-module', []);
var ctrl = app.controller('main-controller', function($scope, ToolService) {
$scope.somethingWasClicked = function() {
ToolService.runTimeoutExample();
}
});
Run Code Online (Sandbox Code Playgroud)
这是问题,当点击的按钮调用$ scope.somethingWasClicked它转发调用服务时,我得到一个错误,说"this.doSomething不是一个函数".
为什么?我该如何解决这个问题?我很难找到一种方法来让我的代码像这样运行,而不会在我的控制器中添加不必要的逻辑.
在此先感谢您的帮助
Dmi*_*tin 12
你有2个选择:
1)使用bind()函数对象的方法:
更改超时回调的上下文,以到达控制器this:
this.runTimeoutExample = function(){
$timeout(function(){
this.doSomething();
}.bind(this), 1000);
}
Run Code Online (Sandbox Code Playgroud)
2)创建一个特殊变量self,以保持与主服务功能上下文的链接:
var app = angular.module('test-module');
app.service('ToolService', function($timeout){
var self = this;
self.doSomething = function() {
console.log("y u no referenced as method?!?");
}
self.runTimeoutExample = function(){
$timeout(function(){
self.doSomething();
}, 1000);
}
})
Run Code Online (Sandbox Code Playgroud)
如果每次使用self,您将确保不会发生上下文丢失.