在AngularJS控制器中调用一个函数内的另一个函数

3

我希望在AngularJS中调用一个函数内的另一个函数。例如,我有一个从数据库获取记录的函数,现在我需要在任何函数被调用时都从数据库获取。

控制器:

function SearchCtrl($scope, $http, $element) {

        // i wish to put this into a function and call it in every function like add,search,etc.
        $http.get('php/products.php').success(function(data){
            $scope.products = data;
        });

        $scope.search = function() {
            var elem = angular.element($element);
            var dt = $(elem).serialize();
            dt = dt+"&action=index";
            //alert(dt);
            console.log($(elem).serialize());
            $http({
                method: 'POST',
                url: 'php/products.php',
                data: dt,
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).success(function(data, status) {
                console.log(data);
                $scope.products = data; // Show result from server in our <pre></pre> element
            }).error(function(data, status) {
                $scope.data = data || "Request failed";
                $scope.status = status;
            });
        };

        //~ add
        $scope.add = function() {
            var elem = angular.element($element);
            var dt = $(elem).serialize();
            dt = dt+"&action=add";
            //alert(dt);
            console.log($(elem).serialize());
            $http({
                method: 'POST',
                url: 'php/products.php',
                data: dt,
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).success(function(data, status) {
                $scope.search(); //i wish to call the function like this instead of replicating the code as below each time
                //~ $http.get('php/products.php').success(function(data){
                //~ $scope.products = data;
            }); // Show result from server in our <pre></pre> element
            }).error(function(data, status) {
                $scope.data = data || "Request failed";
                $scope.status = status;
            });
        };

我该怎么做这件事?


因为我正在使用PHP作为我的模型,我认为如果有人使用PHP作为模型并遇到相同的问题,那么这将会有所帮助。 - z22
1个回答

6
如果我正确理解您的问题,您可以将以下代码放置:
// i wish to put this into a function and call it in every function like add,search,etc.
$http.get('php/products.php').success(function (data) {
    $scope.products = data;
});

在您的控制器中将其转换为以下函数:

var getProducts = function () {
    $http.get('php/products.php').success(function (data) {
        $scope.products = data;
    });
};

并且可以在同一个控制器中的任何位置调用它:

getProducts();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接