5 methods for passing parameters on AngularJS pages and 5 methods for angularjs pages

Source: Internet
Author: User

5 methods for passing parameters on AngularJS pages and 5 methods for angularjs pages

There are multiple methods for passing parameters on Angular pages. Based on Different use cases, I will give you five of the most common methods (please refer to the webpage for answers ):

1. webpage jump parameter passing based on ui-router

(1) producer) Place multiple producers, click a target, the page jumps to the corresponding producer page, and the parameter producerId is passed over.

.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 click events, such as ng-click = "toProducer (producerId)". In ProducersCtrl, define page Jump functions (using $ 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 parameter passing

For example, you have N pages, each of which requires the user to fill in the selected information, and finally guide the user to the end of the page for submission. At the same time, the last page must display the information filled in on all the previous pages. In this case, passing parameters through the factory is a reasonable choice (the following code is a simplified version, which can be customized based on your needs ):

. Factory ('myfactory ', function () {// defines the parameter object var myObject = {}; /*** defines the setter function for data transmission * @ param {type} xxx * @ returns {*} * @ private */var _ setter = function (data) {myObject = data ;}; /*** define the getter function for getting data * @ param {type} xxx * @ returns {*} * @ private */var _ getter = function () {return myObject;}; // Public APIs // In the controller, you can call the setter () and getter () Methods to submit or obtain parameters. return {setter: _ setter, getter: _ getter };});

3. Passing Parameters Based on factory and rootScope. broadcast ()

(1) Example: A nested views is defined on a single page. You want all sub-scopes to listen to changes to a specific parameter and make corresponding actions. For example, for a map application, the input element is defined in a state. After the address is entered, the map must be located, and the list in another state must display information about the shops around the location, at this time, Multiple scopes are listening for address changes.

PS: rootScope. broadcast () allows you to easily set global events and enable all subscopes to listen to them.

. Factory ('address', ['$ rootScope', function ($ rootScope) {// defines the address object var address ={} to be returned; // defines the components array, the array includes street, city, country, and other addresses. components = []; // defines the update address function through $ rootScope. $ broadcast () sets the global event 'addressupdated' // All subscopes can listen to the event address. updateAddress = function (value) {this. components = angular. copy (value); $ rootScope. $ broadcast ('ssssupdated') ;}; // return address object return address ;}]);

(2) In the controller that obtains the address:

// Obtain the address dynamically. var component = {addressLongName: xxxx, addressShortName: xx, cityLongName: xxxx, cityShortName: xx, countryLongName: xxxx, countryShortName: xx, postCode: xxxxx}; // defines the address array $ scope. components = []; $ scope. $ watch ('components', function () {// push the component object to $ scope. components array components. push (component); // update components addressFactory in addressFactory. updateAddress (components );});

(3) In the controller that listens for address changes:

// Use the global event 'addresses' defined in addressFactory to listen for address changes $ scope. $ on ('ssssupdated', function () {// listen for address changes and obtain the corresponding data var street = address. components [0]. addressLongName; var city = address. components [0]. cityLongName; // you can perform operations by obtaining the address data. For example, if you want to obtain the store around the address, the following code creates a shopFactory for yourself. getShops (street, city ). then (function (data) {if (data. status = 200) {$ scope. shops = data. shops;} else {$ log. error ('Sorry, an error occurred while obtaining the store data around the location: ', data );}});});

4. webpage jump parameter passing based on localStorage or sessionStorage

Note: When passing parameters through LS or SS, you must listen to the variables. Otherwise, when the parameters change, the end of the obtained variables will not be updated. AngularJS has some ready-made WebStorage dependency options, for example, corner stone/ngStorage · GitHub, grevory/angular-local-storage · GitHub. The following describes the process of passing Parameters Using ngStorage:

(1) Upload parameters to localStorage-Controller

// Define and initialize the counter attribute $ scope in localStorage. $ storage = $ localStorage. $ default ({counter: 0}); // assume that the updateCounter () method in a factory (this example is now named counterFactory) // It can be used to update the countercounterFactory parameter. updateCounter (). then (function (data) {// upload the new counter value to localStorage $ scope. $ storage. counter = data. counter ;});

(2) monitor Parameter Changes in localStorage-Controller B

$ Scope. counter = $ localStorage. counter; $ scope. $ watch ('counter', function (newVal, oldVal) {// listen for changes and obtain the latest parameter value $ log. log ('newval: ', newVal );});

5. Page parameter passing based on localStorage/sessionStorage and Factory

Due to the different requirements for parameter passing, combining different methods helps you build code with low coupling to facilitate expansion and maintenance.

Example: Application Authentication (authorization ). After a user logs on, the backend returns a time-limited token. the user can access the application next time and obtain the user permission by detecting the token and related parameters, therefore, you do not need to log on again to enter the corresponding page (Automatically Login ). Second, all APIs must inject tokens in the HTTP header to transmit data with the server. At this point, we can see that token plays an important role: (a) it is used to detect user permissions, and (B) it ensures the security of front-end data transmission. The following example uses GitHub-activelee/ngStorage: localStorage and sessionStorage done right for AngularJS. and GitHub-Narzerus/angular-permission: Simple route authorization via roles/permissions.

(1) define a factory named auth. service. js to process authentication-related business logic, such as login, logout, checkAuthentication, and getAuthenticationParams. Skip other services here and focus only on the Authentication part.

(Function () {'use strict '; angular. module ('myapp '). factory ('authservice', authService);/** @ ngInject */function authService ($ http, $ log, $ q, $ localStorage, PermissionStore, ENV) {var apiUserPermission = ENV. baseUrl + 'user/permission'; var authServices = {login: login, logout: logout, getAuthenticationParams: getAuthenticationParams, checkAuthentication: checkAuthentication}; return authServ Ices; //////////////// *** defines the processing error function, Private function. * @ Param {type} xxx * @ returns {*} * @ private */function handleError (name, error) {return $ log. error ('xhr Failed for '+ name + '. \ n', angular. toJson (error, true);}/*** defines the login function and public function. * If the logon succeeds, the token returned by the server is saved to localStorage. * @ Param {type} xxx * @ returns {*} * @ public */function login (loginData) {var apiLoginUrl = ENV. baseUrl + 'user/login'; return $ http ({method: 'post', url: apiLoginUrl, params: {username: loginData. username, password: loginData. password }}). then (loginComplete ). catch (loginFailed); function loginComplete (response) {if (response. status = 200 &&_. includes (response. data. authorities, 'admin ')) {// Store the token to localStorage. $ LocalStorage. authtoken = response. headers (). authtoken; setAuthenticationParams (true);} else {$ localStorage. authtoken = ''; setAuthenticationParams (false) ;}} function loginFailed (error) {handleError ('login () ', error) ;}/ *** defines the logout function, public functions. * Clears data in localStorage and PermissionStore. * @ Public */function logout () {$ localStorage. $ reset (); PermissionStore. clearStore () ;}/ *** defines the setter function for passing data, Private function. * Sets the isAuth parameter. * @ Param {type} xxx * @ returns {*} * @ private */function setAuthenticationParams (param) {$ localStorage. isAuth = param;}/*** defines the getter function for getting data, a public function. * Gets the isAuth and token parameters. * Using setter and getter functions, you can avoid using the $ watch variable mentioned in Method 4. * @ Param {type} xxx * @ returns {*} * @ public */function getAuthenticationParams () {var authParams = {isAuth: $ localStorage. isAuth, authtoken: $ localStorage. authtoken}; return authParams;}/** Step 1: Check whether the token is valid. * If the token is valid, go to step 2. ** Step 2: Check whether the user still belongs to the admin permission. ** the function returns true only when the preceding two conditions are met. Otherwise, false is returned. * See angular-permission for how it works. https://github.com/Narzerus/angular-permission/wiki/Managing-permissions */function checkAuthentication () {var deferred = $ q. defer (); $ http. get (apiUserPermission ). success (function (response) {if (_. includes (response. authorities, 'admin') {deferred. resolve (true);} else {deferred. reject (false );}}). error (function (error) {handleError ('checkauthentication () ', error); deferred. reject (false) ;}); return deferred. promise ;}}})();

(2) A file named index. run. js is defined to automatically run the permission detection code during application loading.

(Function () {'use strict '; angular. module ('myapp '). run (checkPermission);/** @ ngInject * // *** angular-permission version 3.0.x. * https://github.com/Narzerus/angular-permission/wiki/Managing-permissions. ** Step 1: Run authService. getAuthenticationParams () function. * returns true: the user has successfully logged in. Therefore, the isAuth and authtoken parameters are stored in localStorage. * False is returned: The user may have logged out or accessed the application for the first time. Therefore, force the user to enter the user name and password to log on to the logon page. ** Step 2: run the authService. checkAuthentication () function. * return true: the user's token is still valid, and the user still has the admin permission. Therefore, you do not need to log on manually. The page is automatically redirected to the admin page. * False is returned: either the User token has expired or the user does not belong to the admin permission. Therefore, force the user to enter the user name and password to log on to the logon page. */Function checkPermission (PermissionStore, authService) {PermissionStore. definePermission ('admin', function () {var authParams = authService. getAuthenticationParams (); if (authParams. isAuth) {return authService. checkAuthentication () ;}else {return false ;}});}})();

(3) defines a file named authInterceptor. service. js, which is used to inject a token into the header of all the HTTP requests of the application. For AngularJS Interceptor, see AngularJS.

(Function () {'use strict '; angular. module ('myapp '). factory ('authinterceptorservice', authInterceptorService);/** @ ngInject */function authInterceptorService ($ q, $ injector, $ location) {var authService = $ injector. get ('authservice'); var authInterceptorServices = {request: request, responseError: responseError}; return authInterceptorServices; /////////////// inject token into all HTTP requests Headers S. Function request (config) {var authParams = authService. getAuthenticationParams (); config. headers = config. headers | {}; if (authParams. authtoken) config. headers. authtoken = authParams. authtoken; return config | $ q. when (config);} function responseError (rejection) {if (rejection. status = 401) {authService. logout (); $ location. path ('/login');} return $ q. reject (rejection );}}})();

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.