VivekDev
VivekDev

Reputation: 25517

Uncaught TypeError: fn is not a function error in AngularJS web page

I am a newbie on AngularJS. I have the following angularJS code

(function () {
    getDataFactory = function ()
    {
        return {
            callWebApi: function (reqData)
            {
                alert(reqData);
            }
        }
    }
    patientCategoryController = function ($http, $scope, getDataFactory) {
        // The following line is the culprit. If this is commented, I dont get the error. 
        // But it works, ie. when UNcommented, I get the messagebox showing     
        // "someDataToPass"!! So whats wrong???
        angular.element(document).ready(getDataFactory.callWebApi('someDataToPass'));
    }
    patientCategoryController.$inject = ['$http', '$scope', 'getDataFactory'];
    angular.module('demoApp', []);
    angular.module('demoApp').controller('patientCategoryController', patientCategoryController);
    angular.module('demoApp').factory('getDataFactory', getDataFactory);    
}());

I found the method call

angular.element(document).ready(getDataFactory.callWebApi('someDataToPass')); 

is the problem. So I am missing some thing very basic. Can someone please guide me on this. The HTML is absolute basic skeleton. I get this error in Chrome browser, right click and then select inspect page element.

Upvotes: 0

Views: 1936

Answers (2)

Shomz
Shomz

Reputation: 37701

You're supposed to pass the function body as a ready parameter, not the function return value, so this:

angular.element(document).ready(getDataFactory.callWebApi('someDataToPass'));

should become:

angular.element(document).ready(function(){
   getDataFactory.callWebApi('someDataToPass');
})

See it here: https://api.jquery.com/ready/

Upvotes: 3

Constantine Poltyrev
Constantine Poltyrev

Reputation: 1034

You are passing a void function result do the document.ready method. Here're two possible fixes:

  1. Using document.ready

angular.element(document).ready(function(){
  getDataFactory.callWebApi('someDataToPass'));
});

  1. Not using document.ready

    getDataFactory.callWebApi('someDataToPass'));

Upvotes: 3

Related Questions