AngularJS 'this' reference in $timeout function not working
You have 2 options:
1) Using bind()
method of the function object:
Change the context of the timeout callback, to reach the controller this
:
this.runTimeoutExample = function(){ $timeout(function(){ this.doSomething(); }.bind(this), 1000);}
2) Create a special variable self
, to keep the link to main service function context:
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); }})
If every time using self
, you'll be sure that no context lost will happen.
Read more about the context of a function.
the function inside timeout has a different scope as it is not a function belonging to the controller. Assign this
to a variable before timeout, and then use that variable:
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(){ var self = this; $timeout(function(){ self.doSomething(); }, 1000);}})
var app = angular.module('test-module',[]);app.service('ToolService', function($timeout){ function doSomething() { console.log("y u no referenced as method?!?"); } this.runTimeoutExample = function(){ $timeout(function(){ doSomething(); }, 1000); }}); app.controller('main-controller', function($scope, ToolService) { $scope.somethingWasClicked = function() { ToolService.runTimeoutExample(); };});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><div ng-app="test-module" ng-controller="main-controller"> <input type="button" value="click" ng-click="somethingWasClicked()"> </div>