Summary of pits in ANGULARJS mobile development

Source: Internet
Author: User
Tags call back

The use of ANGUALRJS development mobile app has been nearly half a year, and gradually accumulated a lot of angularjs problems, especially for the use of jquery developers, go to angularjs or need to overcome a lot of problems. Unlike jquery, which focuses on DOM operations, Angularjs is centered on the view model and two-way bindings.

The following assumes that you already know the concept of front-end MVC and have some experience with AngularJS, and beginners may read it more obscures. The summary of this article will cover some of the problems that are specific to mobile devices.

problems with DOM operations

Avoid using JQuery to manipulate the DOM, including adding element nodes, removing element nodes, getting element content, hiding or displaying elements. You should use directives to implement these actions, and if necessary, write your own directives.

        in Web site Web front-end development, if you find it hard to change habits, Then consider removing jQuery from your Web page. True,   in the AngularJS; $http Span style= "line-height:24.3099994659424px" >  service is very powerful, basically can replace jQuery Ajax function, and AngularJS embedded jqlite--its internal implementation of a Jque Ry subset, contains the common Jquery dom operation methods, event bindings and so on. But this is not to say that using ANGULARJS can not use JQuery. If your page is loaded with jquery then AngularJS will take precedence over your jquery, otherwise it will fall back to Jqlite.

If it is mobile app or mobile Web development, it is recommended not to introduce jquery, if you really need some features of jquery, introduce Zepto.js bar. But please believe me, with ANGULARJS, you don't need jquery!

The situation where you need to write your own directives is usually when you use a third-party jQuery plugin. Because the plug-in changes the form value outside of AngularJS, it does not immediately react to the Model. For example, we use more jQueryUI DatePicker plug-ins, when you select a date, the plugin will fill the date string into the input box. The View changed, but did not update the Model, because $(‘.datepicker‘).datepicker(); this code does not belong to the AngularJS management scope. We need to write a directive to get the DOM changes to be updated in the Model immediately.

var directives = Angular.module (' directives ', []); Directives.directive (' DatePicker ', function () {   return function (scope, element, attrs) {       Element.datepicker ( {           inline:true,           dateformat: ' dd.mm.yy ',           onselect:function (datetext) {               var Modelpath = $ (this). attr (' Ng-model ');               PutObject (Modelpath, scope, datetext);               Scope. $apply ();});}   );

and introduce this directive in HTML.

<input type= "text" DatePicker ng-model= "Myobject.mydatevalue"/>
       Directive is in the HTML to write custom tag attributes, to achieve the role of plug-ins, effectively supplementing the function of HTML. This declarative syntax extends the HTML. It is recommended that the common features and page components in the project are packaged into directive, easy to use and code maintained.

It is important to note that there is a Angularui project that provides a lot of directive for us to use, including plugins in the Bootstrap framework and other popular UI components based on jQuery. The AngularJS community is now active and the ecosystem is sound.

Value in the Ngoption

        It's a big hole. If you go to view ngoption generated  <SELECT>  <OPTION>   option values (per  <option value=" XXX,   's value section), that's definitely vain. Because the value here will always be the index of the inner element of the AngularJS, not the form option value you specified.

Or to change the concept, AngularJS is no longer using forms to interact with the data, but with Model. Use the $http to submit the Model, which is used in PHP file_get_contents(‘php://input‘) to get the data submitted by the front end.

Question of Input type= ' number '

AngularJS in some versions, the Ng-change method on a mobile device fails when the input box is set to type= ' number '.

Problem with {{}}

When the page is initialized, the user may see {{}} and then flash before the real content appears.
Workaround:

    1. Use ng-cloak directive to hide it
    2. Replace {{}} with Ng-bind
Separating the interface from the business logic

The controller should not refer directly to the DOM, but should control the behavior of the view. For example, "What happens if a user operates X", "where can I get x?" ”

The Service should not refer directly to the DOM in most cases, it should be a singleton (singletons), independent of the interface, regardless of the view's logic. Its role is simply to "do X operations".

DOM operations should be placed inside the directives.

Reuse existing functions as much as possible

The features you write are probably AngularJS already implemented, and some code can be abstracted out and reused, using a more Angular approach. In short, many of JQuery's cumbersome code can be replaced.

1. ng-repeat

Ng-repeat is very useful. When Ajax obtains data from the server, we often use jQuery (as described above) to add more elements to some of the HTML container nodes, which is bad practice in AngularJS. With the ng-repeat everything becomes very simple. Define an array (model) in your $scope to hold the data pulled from the server, and then use Ng-repeat to bind it to the DOM. The following example initializes the model that defines the friends

<div ng-init= "Friends = [{name: ' John ', age:25}, {name: ' Mary ', age:28}]" >    I have {{friends.length}} friends. They be:    <ul>        <li ng-repeat= "friend in Friends" >            [{{$index + 1}}] {{friend.name}} Friend.age}} years old.        </li>    </ul></div>

2. ng-show

Ng-show is also very useful. It is common to use JQuery to control the display of interface elements based on conditions. But Angular has a better way to do that. Ng-show (and Ng-hide) can decide to hide and display based on Boolean expressions.

For arrays or strings, you can control the display with Strxxxx.length, otherwise it will not work on the mobile device.

Similar built-in directives and ng-disabled, Ng-switch, etc., are used for conditional control, simple syntax, and are very powerful.

3. ng-class

Ng-class is used to conditionally add class to elements, and we used to do it with jQuery. Angular in the Ng-class of course better use, example:

<div ng-class= "{errorclass:iserror, warningclass:iswarning, Okclass:!iserror &&!iswarning}" >...</ Div>


Here Ng-class accepts an object, key is the CSS class name, the value is $scope variable control conditional expression, other similar built-in directives also have Ng-class-even and ng-class-odd, very practical.

Ng-show and Ng-if use scenario issues

Using ng-show and ng-if to control the display of page elements, but 2 are different, Ng-if will dynamically create dom,ng-show just toggle the display of the existing DOM, equivalent to set style= "Display:none", If you use CSS pseudo-classes such as before and after to control the display, problems may occur and you need to use ng-show and ng-if as appropriate.

$watch and $apply

AngularJS's two-way data binding is the most exciting feature, but it's not all-powerful magic, and in some cases you need to make some minor corrections.

When you use Ng-model, Ng-repeat, and so on to bind the value of an element, AngularJS creates a $watch for that value, as long as the value changes in the range of AngularJS, and all the places are updated synchronously. While you are writing custom directive, you need to define your own $watch to implement this automatic synchronization.

Sometimes you change the value of the model in the code, and the view is not updated, which is often encountered in custom event bindings. You will need to manually invoke scope. $apply () to trigger an interface update. This is illustrated in the example above DatePicker. Third-party plug-ins may have call back, and we can also write the callback function as an anonymous function as a parameter in $apply ().

Combine ng-repeat and other directives.

Ng-repeat is useful, but it is bound to the DOM and it is difficult to use other directives on the same element (such as Ng-show, Ng-controller, and so on).

If you want to use a directive for the entire loop, you can wrap a parent element outside the repeat to write directive there, and if you want to use a directive for each element inside the loop, put it on a sub-node of the ng-repeat.

Issues with Scope

Scope should be read-only in the templates template, and it should be write-only in the controller. The purpose of Scope is to refer to model, not to be model. Model is the JavaScript object we define.

$rootScope can be used, but it's likely to be abused.

Scopes form a certain hierarchical relationship in AngularJS, the tree structure must have a root node. Usually we don't have it, because almost every view has a controller and a corresponding scope of its own.

But occasionally there is some data that we want to apply globally to the entire app, when we can inject the data into $rootScope. Because other scopes inherit the root scope, the injected data is available for ng-show such as directive in the local $scope.

Of course, global variables are evil and you have to use $rootScope carefully. In particular, do not use it for code, but just to inject data. If you really want to write a function in $rootScope, it's best to write it into the service so it's only injected when it's used, and it's easier to test.

Conversely, if a function simply stores and returns some data, do not create it as a service.

the problem of prototype inheritance for sub-scopes

For starters, this is a big hole. The inheritance of scope variables is based on the JavaScript prototype inheritance mechanism, which requires special attention when working with scopes-related directives such as Ng-template,ion-modal, and the associated lookup order is not covered here.





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.