Four ways to switch and transmit values between angular--pages

Source: Internet
Author: User

Copyright belongs to the author.
Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
Ye Huang
Links: https://www.zhihu.com/question/33565135/answer/69651500
Source: Know

1. Ui-router-based page jump parameters
(1) In Angularjs app.js with ui-router definition routes, such as now have two pages, a page (producers.html) placed multiple producers, click on one of the targets, the page jumps to the corresponding producer page, and will producerid this parameter Number of passes.

. State (' producers ', {    URL: '/producers ',    templateurl: ' views/producers.html ',    controller: ' Producersctrl '}). State (' producer ', {    URL: '/producer/:p roducerid ',    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 (using Ui-router's $ State.go interface):

. Controller (' Producersctrl ', function ($scope, $state) {    $scope. toproducer = function (Producerid) {        $state. Go (' producer ', {Producerid:producerid};};}    );

  


(3) in Producerctrl, obtain the parameter Producerid through the $stateparams of Ui-router, for example:

. Controller (' Producerctrl ', function ($scope, $state, $stateParams) {   var producerid = $stateParams. Producerid;});

  

2. Factory-based page jump parameters
Example: You have n pages, each page requires user to fill in the information, and ultimately guide the user to the end of the submission, and the next page to display all the previous pages filled with information. It is a reasonable choice to use factory for this time (the following code is a simplified version that can be customized according to the requirements):

. Factory (' MyFactory ', function () {    //Definition factory Returns the object    var myservices = {};        Define Parameter Object    var myObject = {};        /**     * Defines a set function that passes data     * @param {type} XXX     * @returns {*}     * @private *    /var _set = function (data) { C11/>myobject = data;         };    /**     * Defines the GET function that gets the data     * @param {type} XXX     * @returns {*}     * @private *    /var _get = function () {        return myObject;    };    Public APIs    myservices.set = _set;    Myservices.get = _get;        The function of the set () and get () methods can be implemented in controller to commit or get parameters    return myservices;  });

  


3. Parameters based on factory and $rootscope. $broadcast ()
(1) Example: In a single page defined nested views, you want to let all sub-scopes listen to a parameter changes, and make the corresponding action. For example, a map application, a $state defines the element input, enter the address, the map to locate, while the other state of the list to show the location of the stores around the information, at this time, multiple $scope are listening to address changes.
PS: $rootScope. $broadcast () can be very convenient to set global events and let all child scopes be heard.

. Factory (' Addressfactory ', [' $rootScope ', function ($rootScope) {    //define the Address object to return       var address = {};        Define the components array, including streets, cities, countries, etc.    address.components = [];    Define update address function, set global event ' addressupdated ' through $rootscope. $broadcast ()    //All child scopes can listen to the event    address.updateaddress = function (value) {this.components = Value.slice (); $rootScope. $broadcast (' addressupdated ');    };        Return address object return addressed    ;}]);

  


(2) in the Controller that obtains the address:

Dynamically get addresses, interface methods omit var component = {    addresslongname:xxxx,    addressshortname:xxxx,    citylongname:xxxx,    cityshortname:xxxx         };//defines an array of addresses $scope.components = []; $scope. $watch (' Components ', function () {    // Pushes the component object into the $scope.components array    components.push (component);    Update the Components addressfactory.updateaddress in Addressfactory    ;});

  


(3) in the controller that listens for the change of address:

The global event ' addressupdated ' listener address change $scope defined in Addressfactory. $on (' addressupdated ', function () {   //listen for address changes and get corresponding data   var street = address.components[0].addresslongname;   var city = address.components[0].citylongname;   By obtaining the address data can do related operations, such as to obtain the address around the shop, the following code for my fictitious   shopfactory.getshops (Street, City). Then (data) {       if ( Data.status = = = () {          $scope. Shops = Data.shops;         } else{          $log. Error (' Sorry, get an error in the location surrounding the store data: ', Data ');});}   );

  


4. Page jump parameters based on Localstorage or sessionstorage
Note: With LS or SS parameters, be sure to listen to variables, otherwise when the parameter changes, get one end of the variable will not be updated. Angularjs have some ready-made webstorage dependency to use, such as Gsklee/ngstorage Github,grevory/angular-local-storage GitHub. The following is a brief description of the process using Ngstorage:
(1) Upload parameters to Localstorage-controller A

Defines and initializes the counter property $scope in localstorage. $storage = $localStorage. $default ({    counter:0});// Suppose that the Updatecounter () method in a factory (this example is named Counterfactory)//Can be used to update the parameters Countercounterfactory.updatecounter (). Then ( function (data) {    //To upload the new counter value to the Localstorage    $scope. $storage. Counter = Data.counter;});

  


(2) Monitoring of parameter changes in Localstorage-Controller B

$scope. Counter = $localStorage. Counter; $scope. $watch (' counter ', function (newval, oldval) {    //listen for changes and get the latest value of the parameter    $log. Log (' newval: ', newval);    });

  

Four ways to switch and transmit values between angular--pages

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.