Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I have a JS function in an AngularJS JS file defined below and I'm calling it.

What would be the correct syntax when calling this function within the JS file itself because I need to do a hard refresh on a grid.

FUNCTION

viewModel.getGridData = function (ajaxUrl, searchValues)
        {
            $http.post(ajaxUrl, { searchCriteria: searchValues })
            .success(function (data)
            {
                viewModel.gridOptions.data = data.kvs;
            });
        };

CALL TO FUNCTION

viewModel.getGridData(ajaxUrl, searchValues);
share|improve this question
    
is viewModel an object of your controller? – MinusFour Oct 15 at 17:38
    
What does not work? – Bergi Oct 15 at 17:40
    
Yes, it's an object. – sagesky36 Oct 15 at 17:40
    
Bergi, the grid does not get refreshed. When I check the values of the variables in the call to the function, they are "undefined". – sagesky36 Oct 15 at 17:42
1  
there isn't enough here to explain exactly what your issue is. Your question says "what is the correct syntax....", but your actual question seems to be why you are getting an undefined value somewhere else, in some code or HTML you haven't even posted here. Please consider fleshing out the question and the actual problem a bit more, and include a Minimal, Complete, and Verifiable example. – Claies Oct 15 at 17:57

1 Answer 1

You should consider making "getGridData" a service function that returns a promise using Angular's internal $http service. This pattern has the benefit of allowing you to reuse your ajax requests in other places within your application and is considered by many to be a best practice.

myApp.factory('SearchService', function($http) {
    return {
      getGridData: function(url, valueObj) {
        return $http.post(url, valueObj);
      }
    }
});

The promise would resolve with the resolution of its internal ajax call, so you would invoke the factory function in your controller (don't forget to inject it as a dependency!) with

SearchService.getGridData(url, valueObject).then(function(result) {
    //you will have access to the result of the Ajax call inside this callback function only.
    //Be sure to bind it for use in other places in your application!
    console.log(result);
})

Relevant reads:

$http docs

angular services docs

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.