如何在控制器之间传输数据 [英] 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.
角度模块:
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"
}]
推荐答案
您可以使用 Angular 服务在控制器之间共享数据.您应该首先创建从您的服务器获取信息的服务
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/
有关 Angular 服务的更多信息,请查看 angularjs 服务文档页面
For more information about angular services take look at angularjs services document page
这篇关于如何在控制器之间传输数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!