如何传输控制器之间的数据 [英] How to transfer data between controllers
问题描述
我试图控制器之间传输数据。
所以这是第一个获取数据我第一个控制器在使用页面加载基于HTTP
函数GetController($范围,$ HTTP){
$ http.defaults.useXDomain = TRUE;
$ HTTP({
方法:POST,网址:的serviceUrl +'/ GetProductsByCategoryOrName',头:{
'授权':apiKey
},
数据:{查询:杂货,的categoryId:976759,PageIndex的0,sortDirection:ASC}
})。然后(函数successCallback(响应){
$ scope.products = response.data;
}),然后(功能errorCallback(错误){
})
}
视图看起来喜欢 -
< DIV NG控制器=GetController>
< DIV CLASS =MDL-细胞NG重复=产品在产品>
&所述; IMG SRC ={{product.largeImage}}/>
< DIV CLASS =MDL-card__title>
< H6类=MDL-card__title文本> {{product.name}}< / H6>
< / DIV>
< / DIV>
< / DIV>
< / DIV>
在哪里我现在需要的是重新绑定此HTML具有相同的请求,但不同的参数。因此,我创建另一个控制器为这个求职
函数的SearchProductsController($范围,$ HTTP){
$ http.defaults.useXDomain = TRUE;
$ scope.searchText =;
$ scope.submit =功能(){
$ HTTP({
方法:POST,网址:的serviceUrl +'/ GetProductsByCategoryOrName',头:{
'授权':apiKey
},
数据:{查询:$ scope.searchText的categoryId:976759,PageIndex的0,sortDirection:ASC}
})。然后(函数successCallback(响应){
$ scope.products = response.data; //如何与GetController的$ scope.products绑定这个?
}),然后(功能errorCallback(错误){
});
}
};
现在需要的 -
我要绑定 $ scope.products
的SearchProductsController
到 GetController的
$ scope.products
,这样它呈现在视图中。
我没有任何想法如何,此刻,我很新的角度做到这一点。
不过,我给一个尝试转移的目的创建服务,但真的没有想法如何将它与它集成。
编辑 -
我已经编辑控制器方法为@Varkal使用服务的建议,还是没能解决掉。
VAR应用= angular.module(productsApp,[])
。服务(的ServiceProvider功能($ HTTP){
this.getDatas =功能getDatas(数据){
返回$ HTTP({
方法:POST,网址:的serviceUrl +'/ GetProductsByCategoryOrName',头:{
'授权':apiKey
},
数据:数据
})
}
返回此
});功能GetController($范围的ServiceProvider){
VAR数据= {查询:杂货,的categoryId:976759,PageIndex的0,sortDirection:ASC};
serviceProvider.getDatas(数据)。然后(功能(响应){
$ scope.products = response.data.data;
});
}功能的SearchProductsController($范围的ServiceProvider){
VAR数据= {查询:$ scope.searchText的categoryId:976759,PageIndex的0,sortDirection:ASC}; $ scope.submit =功能(){
serviceProvider.getDatas(数据)。然后(功能(响应){
的console.log(response.data.data);
$ scope.products = response.data.data;
});
}
};
如果你有2 的意见
与2 控制器
,也可以通过服务和factory.But,在 $范围$ C $共享控制器之间的
$范围
变量(数据) C>变量是本地的本身,以便设置数据到服务或工厂了解特定variable.I preFER使用的工厂,方便流畅黄油控制器。如果你是在一个单独的文件中使用服务
或工厂
你需要在 index.html的
。
app.controller('CTRL1',函数($范围,为myService,$州){
$ scope.variable1 =一;
myService.set($ scope.variable1);
$ state.go('app.thepagewhereyouwanttoshare'); //转至您要共享该变量的页面。
});app.controller('CTRL2',函数($范围,为myService){
的console.log(共享变量+ myService.get());
});
.factory('为myService',函数(){
功能集(数据){
产品=数据;
} 函数的get(){
回报的产品;
} 返回{
设置:设置,
得到:得到
}})
此外,您还可以使用的localStorage
共享数据的目的。的localStorage
带有 angularjs
所以没有必要注入控制器或应用任何额外的依赖。
在具有传递数据的控制器:
localStorage.setItem(产品,$ scope.products);
在控制器,你要访问数据:
localStorage.getItem(产品);
在您的情况:
函数GetController($范围,$ HTTP){
$ http.defaults.useXDomain = TRUE;
$ HTTP({
方法:POST,网址:的serviceUrl +'/ GetProductsByCategoryOrName',头:{
'授权':apiKey
},
数据:{查询:杂货,的categoryId:976759,PageIndex的0,sortDirection:ASC}
})。然后(函数successCallback(响应){
$ scope.products = response.data;
localStorage.setItem(产品,$ scope.products);
}),然后(功能errorCallback(错误){
})
}功能的SearchProductsController($范围,$ HTTP){
$ http.defaults.useXDomain = TRUE;
$ scope.searchText =;
$ scope.submit =功能(){
$ HTTP({
方法:POST,网址:的serviceUrl +'/ GetProductsByCategoryOrName',头:{
'授权':apiKey
},
数据:{查询:$ scope.searchText的categoryId:976759,PageIndex的0,sortDirection:ASC}
})。然后(函数successCallback(响应){
$ scope.products = response.data; //如何与GetController的$ scope.products绑定这个?
$ scope.productsFromGetController = localStorage.getItem(产品);
}),然后(功能errorCallback(错误){
});
}
};
使用工厂
,您需要导航至您想要设置后,因为数据集可以通过在另一个另一套覆盖来获取数据的页面意见。
最后更新:使用服务和工厂
< HTML和GT; < HEAD>
<标题>角JS控制器< /标题>
&所述; SCRIPT SRC =http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\"></script>
&LT; /头&GT; &LT;身体GT;
&LT; H2&GT; AngularJS示例应用程序&LT; / H&GT; &LT; DIV NG-应用=应用程序&GT; &LT; DIV NG控制器=的SearchProductsController&GT;
&LT;输入NG模型=SEARCHTEXT/&GT;
&LT;按钮NG点击=setPlace(SEARCHTEXT)&GT;输入搜索ID&LT; /按钮&GT;
&LT; / DIV&GT;
&LT; DIV NG控制器=GetController&GT;
&LT; DIV NG重复=产品在产品&GT;
&LT; H3&GT; {{product.name}}&LT; / H3 GT&;
&LT; / DIV&GT;
&LT; / DIV&GT;
&LT; / DIV&GT;
&LT;脚本&GT;
VAR应用= angular.module('应用',[]); app.factory(服务功能(){
VAR的数据;
函数的getData(){
返回的数据;
}
功能使用setData(newdata){
数据= newdata;
}
返回{
的getData:的getData,
使用setData:使用setData,
}
})工厂(DataService的功能($ HTTP){
返回{
getComments:功能(roomid){
如果(roomid == 1){
VAR数据= [{名:亚历克斯,地方:加德满都},{名:神,地方:西雅图}];
返回的数据;
}
如果(roomid == 2)
{
VAR newdata = [{名:NEWNAME,地方:加德满都},{名:newname2,地方:西雅图}];
返回newdata;
}
}
}
});
app.controller('的SearchProductsController',函数($范围,服务,$ HTTP,DataService的){
VAR数据= dataService.getComments(1);
Service.setdata(数据);
$ scope.setPlace =功能(SEARCHTEXT){
VAR newdata = dataService.getComments(SEARCHTEXT);
Service.setdata(newdata);
}
})
.controller('GetController',函数($范围,服务){
$范围。$表(函数(){
返回Service.getdata();
},功能(价值){
$ scope.products =价值;
});
})
&LT; / SCRIPT&GT; &LT; /身体GT;
&LT; / HTML&GT;
关于你unworking plunker更新:
这是最接近我可以与你的控制器
的模拟得到:
http://plnkr.co/edit/p9qY1IIWyzYGLehsIOPr?p=$p$pview一>
I am trying to transfer data between controllers.
So this is my first controller that fetches data first when page loads using http-
function GetController($scope, $http) {
$http.defaults.useXDomain = true;
$http({
method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
'Authorization': apiKey
},
data: { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }
}).then(function successCallback(response) {
$scope.products = response.data;
}).then(function errorCallback(error) {
})
}
the view looks like-
<div ng-controller="GetController">
<div class="mdl-cell" ng-repeat="product in products">
<img src="{{product.largeImage}}" />
<div class="mdl-card__title">
<h6 class="mdl-card__title-text">{{product.name}}</h6>
</div>
</div>
</div>
</div>
Where now my need is to rebind this HTML with the same request but different parameters. So I created another controller for this job-
function searchProductsController($scope, $http) {
$http.defaults.useXDomain = true;
$scope.searchText = "";
$scope.submit = function () {
$http({
method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
'Authorization': apiKey
},
data: { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }
}).then(function successCallback(response) {
$scope.products = response.data; //how to bind this with GetController's $scope.products??
}).then(function errorCallback(error) {
});
}
};
What is needed-
I want to bind $scope.products
of searchProductsController
to GetController's
$scope.products
so that it renders in view.
I don't have any idea how to do this at the moment as I am very new to angular. However, I've given a try to create service for transferring purpose but don't really have idea how to integrate it with it.
Edit-
I've edited controller methods as @Varkal suggested using service, Still couldn't get the problem resolved.
var app = angular.module("productsApp", [])
.service("serviceProvider", function ($http) {
this.getDatas = function getDatas(data) {
return $http({
method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
'Authorization': apiKey
},
data: data
})
}
return this
});
function GetController($scope, serviceProvider) {
var data = { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" };
serviceProvider.getDatas(data).then(function (response) {
$scope.products = response.data.data;
});
}
function searchProductsController($scope, serviceProvider) {
var data = { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" };
$scope.submit = function () {
serviceProvider.getDatas(data).then(function (response) {
console.log(response.data.data);
$scope.products = response.data.data;
});
}
};
If you have 2 views
with 2 controllers
, it is possible to share the $scope
variables(data) between controllers through services and factory.But, the $scope
variables are local to the controller itself so set the data to the service or factory to know about that particular variable.I prefer using factory, easy and smooth as butter. If you are using the service
or factory
in a separate file you need to include the file in index.html
.
app.controller('Ctrl1', function($scope, myService, $state) {
$scope.variable1 = "One";
myService.set($scope.variable1);
$state.go('app.thepagewhereyouwanttoshare'); //go to the page where you want to share that variable.
});
app.controller('Ctrl2', function($scope, myService) {
console.log("shared variable " + myService.get());
});
.factory('myService', function() {
function set(data) {
products = data;
}
function get() {
return products;
}
return {
set: set,
get: get
}
})
Also, you can use localstorage
for the purpose of sharing data.localStorage
comes with angularjs
so no need to inject any additional dependency in the controller or app.
In the controller which has to pass data:
localStorage.setItem("products",$scope.products);
In the controller where you to access data:
localStorage.getItem("products");
In your case:
function GetController($scope, $http) {
$http.defaults.useXDomain = true;
$http({
method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
'Authorization': apiKey
},
data: { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }
}).then(function successCallback(response) {
$scope.products = response.data;
localStorage.setItem("products",$scope.products);
}).then(function errorCallback(error) {
})
}
function searchProductsController($scope, $http) {
$http.defaults.useXDomain = true;
$scope.searchText = "";
$scope.submit = function () {
$http({
method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
'Authorization': apiKey
},
data: { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }
}).then(function successCallback(response) {
$scope.products = response.data; //how to bind this with GetController's $scope.products??
$scope.productsFromGetController = localStorage.getItem("products");
}).then(function errorCallback(error) {
});
}
};
Using the factory
, you need to navigate to the page where you want to get the data after you set it since the data set can be overwritten by another set in another views.
FINAL UPDATE: Using service and factory
<html>
<head>
<title>Angular JS Controller</title>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "app" >
<div ng-controller="searchProductsController">
<input ng-model="searchText"/>
<button ng-click="setPlace(searchText)">Enter Search id</button>
</div>
<div ng-controller="GetController">
<div ng-repeat="product in products">
<h3>{{product.name}}</h3>
</div>
</div>
</div>
<script>
var app = angular.module('app', []);
app.factory("Service", function () {
var data;
function getdata() {
return data;
}
function setdata(newdata) {
data = newdata;
}
return {
getdata: getdata,
setdata: setdata,
}
}).factory("dataService",function($http){
return{
getComments:function (roomid){
if(roomid==1){
var data = [{"name":"alex","place":"kathmandu"},{"name":"god","place":"seattle"}];
return data;
}
if(roomid==2)
{
var newdata = [{"name":"newname","place":"kathmandu"},{"name":"newname2","place":"seattle"}];
return newdata;
}
}
}
});
app.controller('searchProductsController',function($scope, Service,$http,dataService) {
var data = dataService.getComments(1);
Service.setdata(data);
$scope.setPlace = function (searchText) {
var newdata = dataService.getComments(searchText);
Service.setdata(newdata);
}
})
.controller('GetController',function($scope, Service) {
$scope.$watch(function () {
return Service.getdata();
}, function (value) {
$scope.products = value;
});
})
</script>
</body>
</html>
Update regarding your unworking plunker:
It is closest i can get with the mock of your controller
:
http://plnkr.co/edit/p9qY1IIWyzYGLehsIOPr?p=preview
这篇关于如何传输控制器之间的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!