There are many ways to pass parameters on Angular pages. According to different use cases, I will give you 5 of the most common ones:
PS: In actual projects, please refer to/johnpapa/angular-styleguideOptimize your code.
1. Jump and transfer parameters based on ui-router
(1) Use ui-router to define routes in AngularJS. For example, there are now two pages, one page () places multiple producers, click one of the targets, the page jumps to the corresponding producer page, and pass the parameter producerId over.
.state('producers', { url: '/producers', templateUrl: 'views/', controller: 'ProducersCtrl' }) .state('producer', { url: '/producer/:producerId', templateUrl: 'views/', controller: 'ProducerCtrl' })
(2) In, define the click event, such as ng-click="toProducer(producerId)", in ProducersCtrl, define the page jump function (using the $ interface of ui-router):
.controller('ProducersCtrl', function ($scope, $state) { $ = function (producerId) { $('producer', {producerId: producerId}); }; });
(3) In ProducerCtrl, get the parameter producerId through the $stateParams of ui-router, for example:
.controller('ProducerCtrl', function ($scope, $state, $stateParams) { var producerId = $; });
2. Jump and transfer parameters based on factory page
For example: You have N pages, each page requires the user to fill in the information, and finally guide the user to submit to the last page. At the same time, the next page must display the information filled in by all the previous pages. At this time, it is a more reasonable choice to use factory to pass arguments (the following code is a simplified version, which can be customized according to the needs):
.factory('myFactory', function () { //Define parameter object var myObject = {}; /** * Define the setter function that passes data * @param {type} xxx * @returns {*} * @private */ var _setter = function (data) { myObject = data; }; /** * Define the getter function to get data * @param {type} xxx * @returns {*} * @private */ var _getter = function () { return myObject; }; // Public APIs // The function of submitting or obtaining parameters can be realized by typing the setter() and getter() methods in the controller return { setter: _setter, getter: _getter }; });
3. Passing parameters based on factory and $rootScope.$broadcast()
(1) For example: Define nested views in a single page. You want all subscopes to listen to changes in a certain parameter and make corresponding actions. For example, in a map application, an element input 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 the information of the shops around the location. At this time, multiple $scopes are listening for the changes in the address.
PS: $rootScope.$broadcast() can easily set global events and let all subscopes listen.
.factory('addressFactory', ['$rootScope', function ($rootScope) { // Define the address object to be returned var address = {}; // Define components array, array including street, city, country, etc. = []; // Define the update address function, set the global event 'AddressUpdated' through $rootScope.$broadcast() // All subscopes can listen to this event = function (value) { = (value); $rootScope.$broadcast('AddressUpdated'); }; // Return address object return address; }]);
(2) In the controller that gets the address:
// Dynamically obtain the address, the interface method is omittedvar component = { addressLongName: xxxx, addressShortName: xx, cityLongName: xxxx, cityShortName: xx, countryLongName: xxxx, countryShortName: xx, postCode: xxxxx }; // Define address array$ = []; $scope.$watch('components', function () { // Push component object into $array (component); // Update components in addressFactory (components); });
(3) In the controller that listens for changes in address:
// Listen to address changes through the global event 'AddressUpdated' defined in addressFactory$scope.$on('AddressUpdated', function () { // Listen to the change of the address and obtain the corresponding data var street = [0].addressLongName; var city = [0].cityLongName; // Related operations can be performed through the obtained address data, such as obtaining the shop around the address. The following code is made by me. (street, city).then(function (data) { if( === 200){ $ = ; }else{ $('Sorry, there was an error in obtaining the data of the shops around this location: ', data); } }); });
4. Page jump to transfer parameters based on localStorage or sessionStorage
Note: When passing parameters through LS or SS, be sure to listen to the variable, otherwise one end of the variable will not be updated when the parameters are changed. AngularJS has some ready-made WebStorage dependencies that can be used, such asgsklee/ngStorage · GitHub,grevory//grevory/angular-local-storage. The following is to use ngStorage to briefly describe the argument transmission process:
(1) Upload parameters to localStorage - Controller A
// Define and initialize the counter property in localStorage$scope.$storage = $localStorage.$default({ counter: 0 }); // Suppose the updateCounter() method in a factory (this example is temporarily named counterFactory)// Can be used to update the counter parameter().then(function (data) { // Upload the new counter value to localStorage $scope.$ = ; });
(2) Listen to parameter changes in localStorage - Controller B
$ = $; $scope.$watch('counter', function(newVal, oldVal) { // Listen to changes and get the latest value of the parameter $('newVal: ', newVal); });
5. Page parameters based on localStorage/sessionStorage and Factory
Due to the different needs of parameter transfer, combining different methods can help you build low-coupling and easy to scale and maintain.
Example: Application Authentication. After the user logs in, the backend passes back a time-limited token. The next time the user accesses the application, the user can obtain user permissions by detecting the token and related parameters, so he does not need to log in again to enter the corresponding page (Automatically Login). Secondly, all APIs need to inject to the HTTP header to transmit data to the server. At this time, we see that token plays an important role: (a) is used to detect user permissions, and (b) ensure the security of front-end and back-end data transmission. Used in the following examplesGitHub - gsklee/ngStorage: localStorage and sessionStorage done right for AngularJS.andGitHub - Narzerus/angular-permission: Simple route authorization via roles/permissions。
(1) Define a factory called to handle business logic related to authentication, such as login, logout, checkAuthentication, getAuthenticationParams, etc. Other businesses are omitted here and only focus on Authentication.
(function() { 'use strict'; angular .module('myApp') .factory('authService', authService); /** @ngInject */ function authService($http, $log, $q, $localStorage, PermissionStore, ENV) { var apiUserPermission = + 'user/permission'; var authServices = { login: login, logout: logout, getAuthenticationParams: getAuthenticationParams, checkAuthentication: checkAuthentication }; return authServices; //////////////// /** * Define the function to handle errors, private functions. * @param {type} xxx * @returns {*} * @private */ function handleError(name, error) { return $('XHR Failed for ' + name + '.\n', (error, true)); } /** * Define login function, public function. * If the login is successful, save the token returned by the server into localStorage. * @param {type} xxx * @returns {*} * @public */ function login(loginData) { var apiLoginUrl = + 'user/login'; return $http({ method: 'POST', url: apiLoginUrl, params: { username: , password: } }) .then(loginComplete) .catch(loginFailed); function loginComplete(response) { if ( === 200 && _.includes(, 'admin')) { // Save token into localStorage. $ = ().authtoken; setAuthenticationParams(true); } else { $ = ''; setAuthenticationParams(false); } } function loginFailed(error) { handleError('login()', error); } } /** * Define the logout function, public function. * Clear data in localStorage and PermissionStore. * @public */ function logout() { $localStorage.$reset(); (); } /** * Defines the setter function that passes data, a private function. * Used to set isAuth parameter. * @param {type} xxx * @returns {*} * @private */ function setAuthenticationParams(param) { $ = param; } /** * Define the getter function that gets data, a public function. * Used to get isAuth and token parameters. * With setter and getter functions, the $watch variable mentioned in the fourth method can be avoided. * @param {type} xxx * @returns {*} * @public */ function getAuthenticationParams() { var authParams = { isAuth: $, authtoken: $ }; return authParams; } /* * Step 1: Check whether the token is valid. * If the token is valid, go to the second step. * * Step 2: Detect whether the user still has admin permission. * * The function will return true only if the above two conditions are met, otherwise false will be returned. * Please refer to the angular-permission documentation for how it works/Narzerus/angular-permission/wiki/Managing-permissions */ function checkAuthentication() { var deferred = $(); $(apiUserPermission).success(function(response) { if (_.includes(, 'admin')) { (true); } else { (false); } }).error(function(error) { handleError('checkAuthentication()', error); (false); }); return ; } } })();
(2) Define a file named to automatically run permission detection code when the application is loaded.
(function() { 'use strict'; angular .module('myApp') .run(checkPermission); /** @ngInject */ /** * angular-permission version 3.. * /Narzerus/angular-permission/wiki/Managing-permissions. * * Step 1: Run the() function. * Return true: The user has successfully logged in before. Therefore, the two parameters isAuth and authtoken have been stored in localStorage. * Return to false: The user may have logout, or accessed the app for the first time. Therefore, the user is forced to enter the user name and password to log in to the login page. * * Step 2: Run the() function. * Return true: The user's token is still valid, and the user still has admin permission. Therefore, there is no need to log in manually, the page will be automatically redirected to the admin page. * Return false: either the user token has expired, or the user no longer has admin permissions. Therefore, the user is forced to enter the user name and password to log in to the login page. */ function checkPermission(PermissionStore, authService) { PermissionStore .definePermission('ADMIN', function() { var authParams = (); if () { return (); } else { return false; } }); } })();
(3) Define a file named token in the header of all HTTP requests requested by the application. About AngularJS's Interceptor, seeAngularJS。
(function() { 'use strict'; angular .module('myApp') .factory('authInterceptorService', authInterceptorService); /** @ngInject */ function authInterceptorService($q, $injector, $location) { var authService = $('authService'); var authInterceptorServices = { request: request, responseError: responseError }; return authInterceptorServices; //////////////// // Inject token into headers of all HTTP requests. function request(config) { var authParams = (); = || {}; if () = ; return config || $(config); } function responseError(rejection) { if ( === 401) { (); $('/login'); } return $(rejection); } } })();
Summarize it yourself; (1) ng-click = "isShow"; $ = true; (2) Configure routing; (3) Use $(./mainchat/);
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.