AngularJS - Passing data between pages
You need to create a service to be able to share data between controllers.
app.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
});
In your controller A:
myService.set(yourSharedData);
In your controller B:
$scope.desiredLocation = myService.get();
Remember to inject myService in the controllers by passing it as a parameter.
If you only need to share data between views/scopes/controllers, the easiest way is to store it in $rootScope. However, if you need a shared function, it is better to define a service to do that.
app.controller('AController', function ($scope, $rootScope) {
$rootScope.varX = "XXX";
});
app.controller('BController', function ($scope, $rootScope) {
console.log("$rootScope.varX:", $rootScope.varX);
});
著作权归作者所有。
商业转载请联系作者获得授权,非商业转载请注明出处。
作者:Ye Huang
链接:http://www.zhihu.com/question/33565135/answer/69651500
来源:知乎 1. 基于ui-router的页面跳转传参(1) 在AngularJS的app.js中用ui-router定义路由,比如现在有两个页面,一个页面(producers.html)放置了多个producers,点击其中一个目标,页面跳转到对应的producer页,同时将producerId这个参数传过去。.state('producers', {
url: '/producers',
templateUrl: 'views/producers.html',
controller: 'ProducersCtrl'
})
.state('producer', {
url: '/producer/:producerId',
templateUrl: 'views/producer.html',
controller: 'ProducerCtrl'
})
(2) 在producers.html中,定义点击事件,比如ng-click="toProducer(producerId)",在ProducersCtrl中,定义页面跳转函数 (使用ui-router的$state.go接口):.controller('ProducersCtrl', function ($scope, $state) {
$scope.toProducer = function (producerId) {
$state.go('producer', {producerId: producerId});
};
});
(3) 在ProducerCtrl中,通过ui-router的$stateParams获取参数producerId,譬如:.controller('ProducerCtrl', function ($scope, $state, $stateParams) {
var producerId = $stateParams.producerId;
});
2. 基于factory的页面跳转传参举例:你有N个页面,每个页面都需要用户填选信息,最终引导用户至尾页提交,同时后一个页面要显示前面所有页面填写的信息。这个时候用factory传参是比较合理的选择(下面的代码是一个简化版,根据需求可以不同定制):.factory('myFactory', function () {
//定义factory返回对象
var myServices = {};
//定义参数对象
var myObject = {}; /**
* 定义传递数据的set函数
* @param {type} xxx
* @returns {*}
* @private
*/
var _set = function (data) {
myObject = data;
}; /**
* 定义获取数据的get函数
* @param {type} xxx
* @returns {*}
* @private
*/
var _get = function () {
return myObject;
}; // Public APIs
myServices.set = _set;
myServices.get = _get; // 在controller中通过调set()和get()方法可实现提交或获取参数的功能
return myServices; });
3. 基于factory和$rootScope.$broadcast()的传参(1) 举例:在一个单页中定义了nested views,你希望让所有子作用域都监听到某个参数的变化,并且作出相应动作。比如一个地图应用,某个$state中定义元素input,输入地址后,地图要定位,同时另一个状态下的列表要显示出该位置周边商铺的信息,此时多个$scope都在监听地址变化。PS: $rootScope.$broadcast()可以非常方便的设置全局事件,并让所有子作用域都监听到。.factory('addressFactory', ['$rootScope', function ($rootScope) {
// 定义所要返回的地址对象
var address = {}; // 定义components数组,数组包括街道,城市,国家等
address.components = []; // 定义更新地址函数,通过$rootScope.$broadcast()设置全局事件'AddressUpdated'
// 所有子作用域都能监听到该事件
address.updateAddress = function (value) {
this.components = value.slice();
$rootScope.$broadcast('AddressUpdated');
}; // 返回地址对象
return address;
}]);
(2) 在获取地址的controller中:// 动态获取地址,接口方法省略
var component = {
addressLongName: xxxx,
addressShortName: xxxx,
cityLongName: xxxx,
cityShortName: xxxx
}; // 定义地址数组
$scope.components = []; $scope.$watch('components', function () {
// 将component对象推入$scope.components数组
components.push(component);
// 更新addressFactory中的components
addressFactory.updateAddress(components);
});
(3) 在监听地址变化的controller中:// 通过addressFactory中定义的全局事件'AddressUpdated'监听地址变化
$scope.$on('AddressUpdated', function () {
// 监听地址变化并获取相应数据
var street = address.components[0].addressLongName;
var city = address.components[0].cityLongName; // 通过获取的地址数据可以做相关操作,譬如获取该地址周边的商铺,下面代码为本人虚构
shopFactory.getShops(street, city).then(function (data) {
if(data.status === 200){
$scope.shops = data.shops;
}else{
$log.error('对不起,获取该位置周边商铺数据出错: ', data);
}
});
});
4. 基于localStorage或sessionStorage的页面跳转传参注意事项:通过LS或SS传参,一定要监听变量,否则参数改变时,获取变量的一端不会更新。AngularJS有一些现成的WebStorage dependency可以使用,譬如gsklee/ngStorage · GitHub,grevory/angular-local-storage · GitHub。下面使用ngStorage来简述传参过程:(1) 上传参数到localStorage - Controller A// 定义并初始化localStorage中的counter属性
$scope.$storage = $localStorage.$default({
counter: 0
}); // 假设某个factory(此例暂且命名为counterFactory)中的updateCounter()方法
// 可以用于更新参数counter
counterFactory.updateCounter().then(function (data) {
// 将新的counter值上传到localStorage中
$scope.$storage.counter = data.counter;
});
(2) 监听localStorage中的参数变化 - Controller B$scope.counter = $localStorage.counter;
$scope.$watch('counter', function(newVal, oldVal) {
// 监听变化,并获取参数的最新值
$log.log('newVal: ', newVal);
});
http://www.zhihu.com/question/33565135
service 到底这么用?
...
AngularJS - Passing data between pages的更多相关文章
- [转]Passing data between pages in JQuery Mobile mobile.changePage
本文转自:http://ramkulkarni.com/blog/passing-data-between-pages-in-jquery-mobile/ I am working on a JQue ...
- angular-ui-router state.go not passing data to $stateParams
app.js中定义了一个state如下,url接收一个id参数 $stateProvider.state("page.details", { url: "/details ...
- [AngularJS] Accessing Data in HTML -- controllerAs, using promises
<!DOCTYPE html> <html> <head> <title>Access Data From HTML</title> < ...
- AngularJS Tabular Data with Edit/Update/Delete
效果 首先,我们先建立一些数据,当然你可以从你任何地方读出你的数据 var app = angular.module('plunker', ['ui.bootstrap']); app.control ...
- [React Native] Passing data when changing routes
The way you make HTTP requests in React Native is with the Fetch API. In this video we'll talk about ...
- [Angular 2] Passing data to components with @Input
@Input allows you to pass data into your controller and templates through html and defining custom p ...
- [Angular 2] Passing data to components with 'properties'
Besides @Input(), we can also use properties on the @Component, to pass the data. import {Component, ...
- angularjs post data
//post json 时收不到数据,目前只找到方法post form形式的key-value值 //关键是设置 headers: { 'Content-Type': 'application/x- ...
- 3D Computer Grapihcs Using OpenGL - 07 Passing Data from Vertex to Fragment Shader
上节的最后我们实现了两个绿色的三角形,而绿色是直接在Fragment Shader中指定的. 这节我们将为这两个三角形进行更加自由的着色——五个顶点各自使用不同的颜色. 要实现这个目的,我们分两步进行 ...
随机推荐
- jQuery事件绑定.on()简要概述及应用
原文地址:http://www.jquerycn.cn/a_5346 前几天看到事件委托的时候,关于live()方法讲的不是很详细,就去搜了一下关于live()和delegate()的,最后看 ...
- linux文件权限查看及修改(实用)
查看Linux文件的权限:ls -l 文件名称 查看linux文件夹的权限:ls -ld 文件夹名称(所在目录) 修改文件及文件夹权限: sudo chmod -(代表类型)×××(所有者)×××(组 ...
- 界面布局之表格布局TableLayout+TableRow
一.基础知识: TableLayout置底,TableRow在TableLayout的上面,而Button.TextView等控件就在TableRow之上, 另外,TableLayout之上也可以单独 ...
- Express+mysql的博客(1)
学了东西一定要自己上手试过才知道是不是真的会了.一直想练练node的使用,本来也没有什么好想法的,经同学提醒了一下,发现其实我可以用node写一个博客.我同学说工作量会非常之大╮(╯_╰)╭那也得先试 ...
- C++ STL vector容器学习
STL(Standard Template Library)标准模板库是C++最重要的组成部分,它提供了一组表示容器.迭代器.函数对象和算法的模板.其中容器是存储类型相同的数据的结构(如vector, ...
- 大数据运算模型 MapReduce 原理
大数据运算模型 MapReduce 原理 2016-01-24 杜亦舒 MapReduce 是一个大数据集合的并行运算模型,由google提出,现在流行的hadoop中也使用了MapReduce作为计 ...
- ant 错误 Specified VM install not found: type Standard VM, name jdk1.6.0_27
ant 错误 ant Specified VM install not found: type Standard VM, name jdk1.6.0_27 原因: 安装了新的jdk, 在workspa ...
- mysql timestamp类型字段的CURRENT_TIMESTAMP与ON UPDATE CURRENT_TIMESTAMP属性
timestamp有两个属性,分别是CURRENT_TIMESTAMP 和ON UPDATE CURRENT_TIMESTAMP两种,使用情况分别如下: 1.CURRENT_TIMESTAMP 当要向 ...
- java-方法练习
一.定义方法的最主要的两个步骤: 1.先明确结果(即返回值类型要先明确) 2. 在实现功能时是否有未知内容参与运算,即明确函数的参数列表(参数类型,参数个数) 例如:定义一个九九乘法表的功能. 思路 ...
- (01-02) odoo8.0_Ubuntu14.04_nginx反代理设置
作者:陈伟明联系 : QQ 942923305 | 微信 toby942923305E-mail: cwm.win@hotmail.com============================== ...