Home > php教程 > PHP开发 > 4 ways to switch between Angular pages and pass values

4 ways to switch between Angular pages and pass values

高洛峰
Release: 2016-12-07 15:46:17
Original
1503 people have browsed it

The example in this article shares the method of switching and transferring values ​​between Angular JS pages for your reference. The specific content is as follows Switching and transferring values ​​between Angular JS pages

1. Page jump and parameter passing based on ui-router
(1 ) Use ui-router to define routing in AngularJS's app.js. For example, there are two pages now. One page (producers.html) places multiple producers. Click one of the targets and the page will jump to the corresponding producer page. At the same time Pass the producerId parameter.

state('producers', {
 url: '/producers',
 templateUrl: 'views/producers.html',
 controller: 'ProducersCtrl'
})
.state('producer', {
 url: '/producer/:producerId',
 templateUrl: 'views/producer.html',
 controller: 'ProducerCtrl'
})
Copy after login


(2) In producers.html, define the click event, such as ng-click="toProducer(producerId)", in ProducersCtrl, define the page jump function (use the $state of ui-router .go interface):

.controller('ProducersCtrl', function ($scope, $state) {
 $scope.toProducer = function (producerId) {
  $state.go('producer', {producerId: producerId});
 };
});
Copy after login


(3) In ProducerCtrl, get the parameter producerId through $stateParams of ui-router, for example:

.controller('ProducerCtrl', function ($scope, $state, $stateParams) {
 var producerId = $stateParams.producerId;
});
Copy after login


2. Factory-based page jump transfer See

for example: you have N pages, each page requires the user to fill in information, and finally guides the user to the last page to submit. At the same time, the latter page should display the information filled in from all previous pages. At this time, it is a more reasonable choice to use factory to pass parameters (the code below is a simplified version and can be customized according to needs):

.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;
  
});
Copy after login


3. Passing parameters based on factory and $rootScope.$broadcast()

(1) Example: Nested views are defined in a single page, and you want all subscopes to monitor changes in a certain parameter and take corresponding actions. For example, in a map application, the input element is defined in a $state. After entering the address, the map needs to be positioned. At the same time, the list in another state needs to display information about the shops surrounding the location. At this time, multiple $scopes are monitoring address changes. .
PS: $rootScope.$broadcast() can be very convenient to set global events and let all child scopes listen to them.

.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;
}]);
Copy after login


(2) In the controller that gets the address:

// 动态获取地址,接口方法省略
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);
});
Copy after login


(3) In the controller that monitors the address change:

// 通过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);
  }
 });
});
Copy after login


4. Based on localStorage or SessionStorage's page jump to transfer parameters

Note: When transferring parameters through LS or SS, you must monitor the variables, otherwise when the parameters change, the end that obtains the variables will not be updated. AngularJS has some ready-made WebStorage dependencies that can be used, such as gsklee/ngStorage · GitHub, grevory/angular-local-storage · GitHub. The following uses ngStorage to briefly describe the parameter transfer process:

(1) Upload parameters to 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;
});
Copy after login


(2) Monitor parameter changes in localStorage - Controller B

$scope.counter = $localStorage.counter;
$scope.$watch('counter', function(newVal, oldVal) {
 // 监听变化,并获取参数的最新值
 $log.log('newVal: ', newVal);
});
Copy after login

That’s it Contents on the four methods of switching between Angular pages and passing values. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template