在angularjs控制器中调用函数内的函数

时间:2012-09-19 10:28:15

标签: php function angularjs

我希望在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;
            });
        };

我该怎么做?

1 个答案:

答案 0 :(得分: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();