3

I have this code and it is working well:

var app = angular.module("resources", []);
    app.service("resourceService", function ($http) {
        return {
            GetAll: function (callBack) {
                $http.get("api/Resource/Get").success(function (data) {
                    callBack(data); 
                })
            }
        }
    });

app.controller("resourcesCtrl", function ($scope, resourceService) {
        $scope.resourceList = [];
        resourceService.GetAll(function (data) { $scope.resourceList = data; });
    });

Using "Controller as" syntax in earlier version of angularjs, you can replace $scope with this. if I do it, my controller will be like:

app.controller("resourcesCtrl", function (resourceService) {
    this.resourceList = [];
    this.setResourceList = function(data){
        this.resourceList = data;
    };
    resourceService.GetAll(this.setResourceList);
});

I add setResourceList, to call it as a method of controller, to have access to the controller context using this. But now, when setResourceList method is running as a callback function, the this is window (as I have a function call, not a method call), so this.resourceList is undefined. I'm seeking any solution to solve the problem, and I think the problem root is replacing $scope with this. Is there any way to access the properties of controller when they are not defined using $scope?

1 Answer 1

2

Use a closure to capture the value of this.

app.controller("resourcesCtrl", function (resourceService) {
    var that = this;
    this.resourceList = [];
    this.setResourceList = function(data){
        that.resourceList = data;
    };
    resourceService.GetAll(this.setResourceList);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much @Maurice. Where is the scope of 'that' now?
Variables in JavaScript are either scoped to a function or global. In this case that is scoped to the controller function and available to each nested function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.