使用$ timeout调用angularjs函数时,“this”(对象)是未定义的

时间:2015-03-08 06:10:39

标签: angularjs service this

我有一个角色服务来管理我的屏幕警报:

angular.module('theapp')
.factory('Alerts', function ($timeout) {

  var unsetMsg = null;

  return {

    alertType: null,
    alertTitle: null,
    alertMessage: null,

    setMessage: function(type, title, message, timed) {     
        var self = this;
        $timeout.cancel(unsetMsg);
        self.alertType = type;
        self.alertTitle = title;
        self.alertMessage = message;

        if (timed)
        {
            unsetMsg = $timeout(self.unsetMessage,5000);
        }
    },

    unsetMessage: function() {
        this.alertType = null;
        this.alertTitle = null;
        this.alertMessage = null;   
        $timeout.cancel(unsetMsg);
    }
  }
  });

设置消息正常工作(从角度控制器调用)并设置超时变量OK,但是当超时(unsetMessage)内调用的函数在5秒延迟后运行时,代码会抛出错误this is undefined 。为什么它不会将自己视为一个对象,我如何实现我想要做的事情?

1 个答案:

答案 0 :(得分:5)

一种可能性是在回调中使用捕获的selfapply,以便传递正确的上下文:

if (timed) {
    unsetMsg = $timeout(function() {
        self.unsetMessage.apply(self);
    }, 5000);
}