0

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?

Simon
  • 296
  • 4
  • 17

1 Answers1

3

What you need to do is store a reference to this in a variable at the beginning of the controller...then add your properties to that variable. Context won't be lost inside callbacks this way.

A common convention is to use var vm for "View Model" but naming of variable is subjective

angular.module('myApp').directive('myDirective', function($http) {
    return {
        controller: function() {
            var vm = this;

            vm.data = '';

            vm.loadData = function(){
                $http.get("someurl.com")
                .success(function(response) {
                    vm.data = response.data; 
                 });
            }

            vm.loadData();
        },
        controllerAs: 'ctrl',
        template: ' <p>{{ctrl.data}}</p> '
    };
});

A popular angular style guide

charlietfl
  • 170,828
  • 13
  • 121
  • 150