gpt4 book ai didi

jquery - Angularjs Controller : how to call a controller in another controller?

转载 作者:行者123 更新时间:2023-12-01 07:14:20 27 4
gpt4 key购买 nike

我有这个列表 Controller ,

define([
'jquery',
'app'
], function ($,app) {

app.controller("ListContacts", function($scope,$route,$http){

$http({
method: 'GET',
url:'php/listContacts.php'
}).then(function(response) {
$scope.contacts = response.data;
});
});
});

我也有这个 search Controller ,我想在 search if query 中调用 list Controller ! ==未定义

define([
'jquery',
'app'
], function ($,app) {

app.controller("SearchContacts", function($scope,$route,$http){

console.log($route.current.params.query);
if($route.current.params.query !== undefined){
// call the list controller
}

$scope.search = function() {
console.log($('#frmSearchContacts').serialize());
$scope.contacts = null;

};

});
});

这可能吗?

编辑

我的路由器,

define([
'app',
'controller/AppCtrl',
'controller/AppCtrl2',
'controller/AppCtrl3',
'controller/ListContacts',
'controller/AddContact',
'controller/UpdateContact',
'controller/SearchContacts'
], function (app) {

'use strict';
//console.log(app);

return app.config(['$routeProvider' , function ($routeProvider) {
$routeProvider
.when("/",
{
templateUrl: "js/template/app.html",
controller: "AppCtrl"
})
.when("/listcontacts",
{
templateUrl: "js/template/list.html",
controller: "ListContacts"
})
.when("/addcontact",
{
templateUrl: "js/template/add.html",
controller: "AddContact"
})
.when("/updatecontact/:id",
{
templateUrl: "js/template/update.html",
controller: "UpdateContact"
})
.when("/searchcontacts",
{
templateUrl: "js/template/search.html",
controller: "SearchContacts"
})
.when("/searchcontacts/:query",
{
templateUrl: "js/template/search.html",
controller: "SearchContacts"
})
.when("/:module/:method/",
{
templateUrl: "js/template/app.html",
controller: "AppCtrl2"
});
}]);


});

最佳答案

从另一个 Controller 调用 Controller 方法实际上不是一个好主意,如下 angular concepts .

对于您的情况,一种解决方案是使用通用服务来获取联系人

app.factory("contactsService",function(){
return {
getContacts: function(){
return $http({
method: 'GET',
url:'php/listContacts.php'
});
}
}
})

并将其注入(inject)到您想要的所有内容中:

app.controller("SearchContacts", function($scope,$route,$http, contactsService){

console.log($route.current.params.query);
if($route.current.params.query !== undefined){
contactsService.getContacts().then(function(response){
$scope.contacts = response.data;
})
}

$scope.search = function() {
console.log($('#frmSearchContacts').serialize());
$scope.contacts = null;
};

});

您也可以使用事件广播,但我认为在这种情况下使用服务是最好的解决方案。

关于jquery - Angularjs Controller : how to call a controller in another controller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20826193/

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