Real-time response of global object change of Angular.js

Source: Internet
Author: User

Angularjs is a front-end JS frame from Google, small in size, but very powerful in design concepts and functionality.

  Tutorial

  Angularjs Chinese Community

  Problem

In a Web application, although we avoid using global variables as sparingly as possible, it is sometimes necessary to have some global variables that are guaranteed to handle certain events on all pages.

In the example in this article, the application needs to receive SMS messages on the Android platform and respond in real time (where the specific implementation plugin is used, the receiving and sending of text messages are simulated with the console), for which we define a JavaScript global object as follows:

1 varNative_accessor = {2     //Send SMS Function3Send_sms:function(phone, message) {4         //Simulation via console5 console.log (phone, message);6         //actual plug-in calls7         //native_access.send_sms ({"Receivers": [{"name": ' Name ', "Phone":p Hone}]}, {"Message_content": Message});8     },9 Ten     //Receive SMS Functions OneReceive_message:function(json_message) { A         if(typeof  This. process_received_message = = = ' function ') { -              This. Process_received_message (json_message); -         } the     }, -  -     //Handling SMS Functions -Process_received_message:function(json_message) { + Message.received_new_item (json_message); -     } + } A  at //functions that are called automatically when receiving text messages - functionnotify_message_received (Message_json) { - native_accessor.receive_message (Message_json); -}

The above code establishes a JavaScript global object native_accessor and a global function notify_message_received (Message_json), where native_ The accessor consists of three different function functions. The notify_message_received (Message_json) function is automatically triggered when a text message is received by the system.

In this example, there is an event registration page, which needs to display all the registered person's phone, after receiving a valid registration text message to automatically update the page. (Of course, you will still be able to receive text messages even if you are not on the Event registration page.) The relevant HTML code for the event registration page is as follows:

1 <div id= "Detail_scope" >2     <ul class= "List-group" >3         <li class= " List-group-item "ng-repeat=" Message in Message_list | By: '-name ' ">4            {{message.name}}5             <span class=" Pull-right ">{{ Message.phone}}</span>6         </li>7     </ul>8 </div>

In the above code, we created a list that shows "name" and "number", with the name at the left number on the right. In order to be able to access the Angularjs template externally, we added an ID tag to the DIV, which can be arbitrary (using the ID tag on any element within the controller).

Next, because in the above code we call the Message.received_new_item (Json_message) method when we receive the text message, now we consider the relevant implementation code:

1 //This part can be ignored, directly see Message.refresh_ui_list ()2Message.received_new_item =function(Message_json) {3     varMessage_text = Message_json.messages[0].message;4     varMessage_phone = Message_json.messages[0].phone;5     varHeader_is_right = message_text.substring (0,2). toUpperCase () = = ' BM ';6     //Check short format letter is not for "BM" head7     if(header_is_right) {8         varMessage_name = message_text.substring (2). Replace (",");9         //Check whether the current activity status allows registrationTen         varActivity_status = Localstorage.getitem ("activity_status") | | "Prepare"; One     if(Activity_status = = "Prepare") { AMessage.sendback_info (Message_phone, "early"); -         } -         Else if(Activity_status = = "Over") { theMessage.sendback_info (Message_phone, "late"); -         } -         Else { -             varMessage_list =Message.get_all_items (); +             //Check if the person is repeatedly enrolled -             if(!message.check_if_repeat (Message_phone)) { +                 varActivity_name =Activity.get_current_item (); AMessage_list.splice (0,0, {name:message_name, Phone:message_phone, activity:activity_name}); at Message.save_all_items (message_list); -                 //here is the page refresh function called -Message.refresh_ui_list (); -Message.sendback_info (Message_phone, "Success"); -             } -         }     in     } - }; to  +  - //functions for automatic page refresh theMessage.refresh_ui_list =function () { *     //extract the scope of the page part as a variable $     varDetail_scope = Angular.element ("#detail_scope"). scope ();Panax Notoginseng     //If the app is not on the page and the variable is undefined, continuing to execute the console will give an error (although it can still be performed) -     if(detail_scope) { the         //$apply methods that require special attention +Detail_scope. $apply (function () { A detail_scope.update_when_receive (); the         }); +     } -};

In the above code, in order to be able to invoke the function within scope of the controller in the global, we extract the scope from Angularjs by means of the angular.element ("#element_id"). You can think of this scope as a JavaScript object at this point. You can then invoke the function in scope using the method called the object function.

It is important to note that the method is called directly, although the corresponding data can be updated, but does not directly affect the page, do not know whether the non-UI thread can not directly modify the UI elements. To do this, we need to call the $apply method, and the required function as the parameter of the method, so that the page can be updated synchronously.

By the way, put the local method called:

1$scope. update_when_receive =function () {2$scope. message_list =Message.read_all_items ($scope. activity_name);3     if($scope. message_list.length! = 0) {4$scope. Member_count = "(". Concat ($scope. message_list.length.toString ()). Concat ("person"));5     }6     Else {7$scope. Member_count = "";8     }9};

The method here implements the function of updating the list and statistics, in view of the fact that this is not important in this article, a little bit over here, complete with the project code see HTTPS://GITHUB.COM/TROTYL/PARTY_BID

If you have questions about any of the contents of this article or would like to provide some comments or suggestions, you can contact us in the comments below or in private messages ~

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.