Steven Tomlinson
Steven Tomlinson

Reputation: 118

Why is $q undefined in the following angularjs example?

At the line var deferred = $q.defer();

When I try to submit a simple form using the following code, I get: TypeError: Unable to get property 'defer' of undefined or null reference.

angular.module('app').controller('enrollCtl', function enrollCtl($q, $http)
{

    // Using 'Controller As' syntax, so we assign this to the vm variable (for viewmodel).
    var vm = this;
    // Bindable properties and functions are placed on vm.

    vm.applicantData = {
        FirstName: "",
        Comment: ""
    };

    vm.registerApplicant = function submitForm($q, $http)
    {

        console.log('posting data::' + vm.applicantData.FirstName)
        var serverBaseUrl = "https://test.com/TestForm";
        var deferred = $q.defer();
        return $http({
            method: 'POST',
            url: serverBaseUrl,
            data: vm.applicantData
        }).success(function (data, status, headers, cfg)
        {
            console.log(data);
            deferred.resolve(data);
        }).error(function (err, status)
        {
            console.log(err);
            deferred.reject(status);
        });
        return deferred.promise;

    };

})

Upvotes: 0

Views: 1764

Answers (1)

Bergi
Bergi

Reputation: 664548

You've declared $q and $http twice as parameters, once at your controller and once at your function. The modules will only get injected in your controller, and the parameters of your function (where they have the value undefined if you call the function with nothing) shadow them.

Notice that you should not use $q.deferred here anyway, just return the promise that $http already gives you:

vm.registerApplicant = function submitForm() {
    console.log('posting data::' + vm.applicantData.FirstName)
    return $http({
//  ^^^^^^
        method: 'POST',
        url: "https://test.com/TestForm",
        data: vm.applicantData
    }).success(function (data, status, headers, cfg) {
        console.log(data);
    }).error(function (err, status) {
        console.log(err);
    });
};

Upvotes: 1

Related Questions