4 ways to switch between Angular pages and pass values
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' })
(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}); }; });
(3) In ProducerCtrl, get the parameter producerId through $stateParams of ui-router, for example:
.controller('ProducerCtrl', function ($scope, $state, $stateParams) { var producerId = $stateParams.producerId; });
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; });
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; }]);
(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); });
(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); } }); });
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; });
(2) Monitor parameter changes in localStorage - Controller B
$scope.counter = $localStorage.counter; $scope.$watch('counter', function(newVal, oldVal) { // 监听变化,并获取参数的最新值 $log.log('newVal: ', newVal); });
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)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











This article continues the learning of Angular, takes you to understand the metadata and decorators in Angular, and briefly understands their usage. I hope it will be helpful to everyone!

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

Do you know Angular Universal? It can help the website provide better SEO support!

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

This article will share with you an Angular practical experience and learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to
