gpt4 book ai didi

php - 在angularjs Controller 中的函数内调用函数

转载 作者:可可西里 更新时间:2023-11-01 00:34:30 24 4
gpt4 key购买 nike

我希望在 angularjs 的另一个函数中调用一个函数。例如。我有一个从数据库中获取记录的函数,现在每次调用任何函数时我都需要从数据库中获取。 Controller :-

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

我该怎么做?

最佳答案

如果我正确阅读了您的问题,您可以输入以下代码:

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

在你的 Controller 中加入这样的函数:

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

并在同一个 Controller 中的任何地方调用它:

getProducts();

关于php - 在angularjs Controller 中的函数内调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12492880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com