2012-09-19 49 views
3

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

我該怎麼做?

+0

爲什麼php標籤? –

+0

,因爲我使用PHP作爲我的模型,我想如果任何人已經與PHP一起工作的模型,並面臨同樣的問題,那麼它會有一些幫助 – z22

回答

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

相關問題