0

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;

    };

})
Seth
  • 10,198
  • 10
  • 45
  • 68

1 Answers1

1

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);
    });
};
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375