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

どうすればいいですか?

4

1 に答える 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();

于 2012-09-19T18:18:41.640 に答える