简体   繁体   English

调用AngularJS javascript函数时的正确语法

[英]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. 我在下面定义的AngularJS JS文件中有一个JS函数,我称之为它。

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. 在JS文件本身中调用此函数时,正确的语法是什么,因为我需要在网格上进行硬刷新。

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. 您应该考虑使“ getGridData”成为一个服务函数,该函数使用Angular的内部$ http服务返回一个承诺。 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 . 这种模式的好处是允许您在应用程序内的其他位置重用ajax请求, 许多人认为这是最佳实践

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 promise将通过其内部ajax调用的解析来解决,因此您可以使用以下命令在控制器中调用factory函数(不要忘记将其作为依赖项注入!)

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 $ http docs

angular services docs 角度服务文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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