Noel Yap
Noel Yap

Reputation: 19758

How to use AngularJS scope.$bind

I have the following controller which works fine:

function Controller() {}

Controller.prototype = {
    getResult: function(project) {
        var that = this;

        jQuery.ajax({
            async: false,
            url: "/my-service/call?project=" + project,
            dataType: "json",
            success: function(data) { 
                that.result = data;
            }
        });
    }
};

I'd like to use AngularJS .scope.$bind to see if I could eliminate the 'var that = this;' hack. But the following doesn't work:

function Controller() {}

Controller.prototype = {
    getResult: function(project) {
        angular.scope.$bind(jQuery.ajax({
            async: false,
            url: "/my-service/call?project=" + project,
            dataType: "json",
            success: function(data) { 
                this.result = data;
            }
        }))();
    }
};

What am I missing?

Upvotes: 3

Views: 3927

Answers (1)

Noel Yap
Noel Yap

Reputation: 19758

Misko Hevery on the angular mailing responded with:

Controller.prototype = {
    getStuff: function(project) {
        jQuery.ajax({
                    async: false,
                    url: "/service/get-stuff",
                    dataType: "json",
                    success: angular.bind(this, function(data) {
                        this.stuff = data;
                    })
                });
    }
};

He also suggested using angular.service.$xhr instead of jQuery.ajax.

Upvotes: 2

Related Questions