I have the following controller and http request.
I'm setting connectionError to false and want to set it to true on the callbackError in the http request.
I get the following error when using this
Cannot set property 'connectionError' of undefined
Everything works fine when I use $scope.
I've read the following article https://toddmotto.com/digging-into-angulars-controller-as-syntax/ which explains a lot about this and scope and kind of understand that in my code below the this that initially sets 'connectionError' to false is not the same this within the callbackError function as this refers to the function it resides in...?!? (well that's currently what I'm interpreting...)
So my question is - is there a way to set the 'connectionError' to true. Or is this a classic example where $scope is better suited?
Code:
var userApp = angular.module('UserApp', []);
userApp.controller('UserListCtrl', ['$scope', '$http', function ($scope, $http){
var type = this;
type.users = [];
// doesn't work
this.connectionError = false;
// works
$scope.connectionError = false;
// get the data
$http.get('./types/users.json')
// on success
.then(function successCallback(response){
type.users = response.data;
},
// on error
function errorCallback(response){
// doesn't work
this.connectionError = true;
// works
$scope.connectionError = true;
});
}]);