I'm working on a angularjs project and I'm trying to implement it as close as possible to angularjs 2.
In angularjs 2 there will be no more ng-controller and $scope, so I'm using directives instead of ng-controller. Also I'm trying to avoid the use of $scope by using the controllerAs-syntax.
My directives would look something like this:
angular.module('myApp').directive('myDirective', function() {
return {
controller: function() {
this.data = '123';
},
controllerAs: 'ctrl',
template: ' <p>{{ctrl.data}}</p> '
};
});
So far everything works fine. The problems start when I'm trying to call a methode or a property on the controller within a callback-function. In this case 'this' is not referencing the actual controller-instance any more.
Example:
angular.module('myApp').directive('myDirective', function($http) {
return {
controller: function() {
this.data = '';
this.loadData = function(){
$http.get("someurl.com")
.success(function(response) {
this.data = response.data; // --> this doesn't work
});
}
this.loadData();
},
controllerAs: 'ctrl',
template: ' <p>{{ctrl.data}}</p> '
};
});
Is there a way to get a reference to my controller-instance within the callback so I can use the controllers methods and properties within the callback?