如何在控制器之间传输数据 [英] How to transfer the data between controllers
问题描述
我倾向于角色并面临一个问题:我有一个SPA,其中包含两个带控制器的部分,数据从json文件返回。显示菜单的第一个控制器,第二个 - 用于添加新项目。现在在json文件中有两个对象,但是当我在第二个控制器中添加第三个项目时,当我返回第一页时它消失了。我该如何解决?我已经读过工厂可以在控制器之间传输数据,但我从来没有使用它。
I tought angular and faced with a problem: I have a SPA which contains two parts with controllers, the data returns from json file. The first conroller for showing the menu, the second - for adding a new item. For now in json file there are two object, but when I added a third item in the second controller, It dissapeared when I return on the first page. How can I fix it? I've read that factory can transfer the data between controllers, but I've never use It.
Angular模块:
Angular module:
var myApp = angular.module("testModule", ['ngRoute']);
myApp.config(function ($routeProvider){
$routeProvider.when('/', {
templateUrl: 'pages/main.html',
controller: 'mainCtrl'
})
.when('/add', {
templateUrl: 'pages/add.html',
controller: 'addCtrl'
})
})
myApp.controller("mainCtrl", function ($scope, $http) {
$http.get("model/data.json").success(function (response) {
$scope.list = response;
})
});
myApp.controller("addCtrl", function ($scope, $http) {
$scope.addAdv = function(newAdv){
$http.get("model/data.json").success(function (response) {
response.push({
name: newAdv.name,
shop: newAdv.shop
});
})
};
});
JSON文件:
[{
"name": "New Item",
"shop": "Titan"
},
{
"name": "New Item1",
"shop": "Titan"
}]
推荐答案
您可以使用角度服务在控制器之间共享数据。
您应首先创建服务以从服务器获取信息
You can use angular services to share data between your controllers. you should first create service for getting information form your server
var app = angular.module('app', ['ngRoute']);
app.service('dataService', function($http) {
var data = {};
data.list = [];
var getData = function(){
$http.get("model/data.json").then(function (response) {
data.list = response.data;
},function(err){});
}
return {
getDataFromServer:getData,
getData:data,
}
});
现在您可以在控制器中使用此服务:
Now you can use this service in your controller:
app.controller("mainCtrl", function ($scope, dataService) {
dataService.getDataFromServer();
});
app.controller("addCtrl", function ($scope, dataService) {
$scope.data = dataService.getData;
$scope.data.list.push({
name:"foo",
shop:"bar"
});
});
这里是jsfiddle代码:
https://jsfiddle.net/xqn5yu8g/
And here is jsfiddle code: https://jsfiddle.net/xqn5yu8g/
有关角度服务的更多信息,请参阅 angularjs服务文档页面
For more information about angular services take look at angularjs services document page
这篇关于如何在控制器之间传输数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!