简体   繁体   中英

Correct syntax when calling an AngularJS javascript function

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM