0

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);
5
  • is viewModel an object of your controller? Commented Oct 15, 2015 at 17:38
  • Yes, it's an object. Commented Oct 15, 2015 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". Commented Oct 15, 2015 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 reproducible example. Commented Oct 15, 2015 at 17:57
  • also, why are you using $http.post for what appears to be something that should be a GET operation? Commented Oct 15, 2015 at 18:01

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.