"this" in javascript is not the same as "this" in other languages. You can think of it more as the context of a function call.
The default call context on a web application is window. However, when calling a function that is a property of an object, the context becomes the object.
So, in your example:
angular.module('myApp', ['ionic'])
.controller('PopupCtrl',function($scope, $ionicPopup) {
//"this" refers to the controller instance here (controllers are created by angular with the "new" operator)
this.testAlert = function() {
//inside of this function, "this" will still be the controller
alert('Alerting!');
};
//"this" is the controller
this.showAlert1 = function() {
//"this" is still the controller
$ionicPopup.alert({
title: 'Don\'t eat that!',
template: 'It might taste good'
}, this).then(function() {
//"this" is no longer the controller. It's probably "window", but it's possible that ionic sets this to some other parameter when it invokes the function.
//since it's not the controller, testAlert() is undefined!
this.testAlert();
});
};
//"this" is the controller
this.showAlert2 = function() {
//"this" is still the controller, and you have assigned _this to also be the controller
var _this = this;
$ionicPopup.alert({
title: 'Don\'t eat that!',
template: 'It might taste good'
}, _this).then(function() {
//"_this" is captured by the closure created by the function call, and it is still the controller, so testAlert() is defined.
_this.testAlert();
});
};
});
You'll often see this in code:
var self = this;
With "self" being used in place of this in order to avoid the confusion that you've encountered.
angular.module('myApp', ['ionic'])
.controller('PopupCtrl',function($scope, $ionicPopup) {
var self = this;
self.testAlert = function() {
alert('Alerting!');
};
self.showAlert1 = function() {
$ionicPopup.alert({
title: 'Don\'t eat that!',
template: 'It might taste good'
}, self).then(function() {
self.testAlert();
});
};
self.showAlert2 = function() {
$ionicPopup.alert({
title: 'Don\'t eat that!',
template: 'It might taste good'
}, self).then(function() {
self.testAlert();
});
};
});