ANGULARJS Project actual Combat! 03:ANGULARJS collaboration with other class libraries (GO)

Source: Internet
Author: User

Angularjs, in my opinion, is a medium-weight framework. It is not as simple as backbone, and not as comprehensive as dojo and Yui. Many times, the attempt to all-encompassing, often appear a lot of sub-module quality underachievement, and change it more difficult. Too thin, the content of the framework is too thin to write too much. Angularjs This relatively moderate style, it is very much in line with my needs.

Currently, Angularjs three of the most sophisticated components I think are data binding (Scope), instruction (Directive), and Dependency injection (Dependency injection), which perform very well. In contrast, its UI components and animations are weaknesses. It can be said that the choice of angularjs means that the jquery-style component library is chosen to compensate for its shortcomings, to complete a Web application must deal with the third-party class library.

Now there are many UI plug-ins written for Angularjs, some combine bootstrap, some combine jquery, although not perfect, are worth reference: http://angular-ui.github.io/

Collaboration with the JQuery class library

Third-party libraries, have to mention the famous jquery, is now basically a domestic web development of the required tools. Its flexible DOM operation makes many web developers addicted to it. Together with a well-established jquery UI Library and a large number of jquery plugins, it's almost an inexhaustible treasure trove. However, can it be combined with ANGULARJS?

Many angularjs fundamentalists have a negative attitude towards this. They believe that since Angularjs is used as a framework for Web applications, it is necessary to avoid interference from other libraries and make pure MVVM pattern applications. Any DOM operation like jquery is unclean. All interface-related, such as DOM operations, are placed in directive so that the page directive without code, consistent with the JSF idea. MVVM,DSL, modular Thinking this is the trend of the web. Well, the idea is good, the fundamentalists are so pure in their minds. But the fact of the matter is that with angularjs we can't live without jquery.

As we all know, angularjs in fact already built-in jquery Lite, and many methods of Angularjs source code are directly using the jquery method. For example, the Angularjs event binding mechanism. Now that the prophets are in use, why should we not? There is nothing wrong with modular thinking, but there is no need to tie your hands and feet. The only thing to keep in mind is not to use jquery's code to break the ANGULARJS structure. My principles are as follows, and the deficiencies also indicate:

    1. Angularjs is used in the important aspects of module partitioning, service, routing, Dependency injection, and only some specific content (usually some UI) uses jquery.
    2. Avoid writing a bunch of jquery code that directly manipulate DOM elements in the controller. Use the Angularjs template binding mechanism.
    3. Common components are extracted using angularjs methods, but the implementation of the components does not have to be entangled in the use of jquery and its plugins.
    4. When using a third-party class library, the variables and functions are named with special tags (usually abbreviated with this class library name).
jquery, it is recommended as a angularjs dependency, before Angularjs loaded in.

In fact, the choice of a framework such as ANGULARJS, medium heavyweight, means you have to add another class library. And jquery, it is recommended as a angularjs dependency, before Angularjs loaded in. Because when I look at the Angularjs API, I've found that many of these features are in fact dependent on jquery. A typical example is the Ng-blur directive on the official website.

<input type= "text" ng-model= "name" ng-blur= "CheckName ()" >

The ng-blur instruction is the instruction that fires when the focus leaves an element. For the example above, the CheckName () function is triggered when the focus leaves the text input box.

It looks simple, but if you really use this command, you'll find it doesn't work at all. After examining the document carefully, I discovered that this was actually a function that the prophets implemented using JQuery's Blur method (and in fact it was not actually implemented and placed in the current version). So even if we wanted to write one, it would be impossible to leave the jquery native repository because the blur method was not encapsulated in the jquery Lite in Angularjs. In other words, full jquery must be loaded before it can be used. So, I simply wrote a label myself:

/**/$compileProvider. directive (function(    ) {return  {        ' A ',        function(scope, elm, attrs) {            elm.bind (  function() {                scope. $apply (Attrs.onblur);}            );        }    };});

That's good enough.

But it's not perfect. Because the $apply method accepts a function problem, it is possible to write directly as above, which may cause Angularjs to run the Times wrong: $apply already in progress

To avoid this problem, the $apply method needs to be processed:

/*Factory Function safeapply * * @description If you find yourself triggering the ' $apply already in progress ' ERROR WH Ile Developing with Angular.js * (for me I find I-hit most often when integrating third party plugins that trigger a lot o F DOM events), * You can use a ' safeapply ' method which checks the current phase before executing your function. * * @param scope, the action scope, mostly is the topmost controller * @param FN, the function which your want to apply int o scope * @see Https://coderwall.com/p/ngisma*/. Factory (' Safeapply ',function($rootScope) {return function(Scope, FN) {varPhase =scope. $root. $ $phase; if(Phase = = ' $apply ' | | phase = = ' $digest ') {            if(FN &amp;&amp; (typeof(fn) = = = ' function ') {fn (); }        } Else{scope. $apply (FN); }    }});

Then the previous onblur label should read:

/**/$compileProvider. directive (function(safeapply    ) {  Return  {        ' A ',        function(scope, elm, attrs) {            Elm.bind ( function () {                safeapply (scope, Attrs.onblur);            })     ;};});

The above code I have been added to my own Angular_extend module, used in their own projects, the effect is very good.

example of encapsulating a jquery plugin into a component in a angularjs way

Icheck is a jquery plugin for beautifying checkboxes and radio buttons across browsers. About its introduction, in http://www.bootcss.com/p/icheck/

In general, it is used by adding a jquery code after the DOM is loaded:

$ (' input '). ICheck ({    false,    true,    ' Icheckbox_ Square-blue ',    ' Iradio_square-blue ',    ' 20% '});

But if we're going to put it in our project, we can't plug in the jquery code that directly operates the DOM, which is neither beautiful nor easy to maintain. In accordance with the previously mentioned principle, it is best to encapsulate it into a angular instruction pattern, which is placed in a public module to invoke. Here I named my new command Ng-icheck. So, we just write in a checkbox or radio HTML tag and add a ng-ickeck. The specific implementation is as follows:

/** Angular directive ng-icheck * * @description Icheck is a plugin of the jquery for beautifying checkbox &amp; Radio, Now I complied it with angular directive * @require jquery, Icheck * @example &lt;input type= "Radio" ng-model= "Paomia N "value=" Kangshifu "ng-icheck&gt; * &lt;input type= "checkbox" class= "Icheckbox" name= "Mantou" ng-model= "Mantou" Ng-icheck checked&gt; */$compileProvider. Directive (' Ngicheck ',function($compile) {return{restrict:A, require:'? Ngmodel ', Link:function($scope, $element, $attrs, $ngModel) {if(!$ngModel) {                return; }            //using ICheck$ ($element). ICheck ({labelhover:false, cursor:true, Checkboxclass:' Icheckbox_square-blue ', Radioclass:' Iradio_square-blue ', Increasearea:' 20% '}). On (' Ifclicked ',function(event) {if($attrs. Type = = "checkbox") {                    //checkbox, $ViewValue = true/false/undefined$scope. $apply (function() {$ngModel. $setViewValue (! ($ngModel. $modelValue = = undefined?false: $ngModel. $modelValue));                }); } Else {                    //radio, $ViewValue = $attrs. Value$scope. $apply (function() {$ngModel. $setViewValue ($attrs. Value);                });        }            }); },    };});

In the above code, it is worth noting that: After using the Icheck plugin, a beautified div will be generated to cover the original checkbox or radio, and the original checkbox or radio will be hidden. Therefore, when we click on them, the events are not triggered directly, so that the model values bound to the checkbox or radio are changed. So we need to rebind the event here, using

$ngModel. $setViewValue ()

method to assign a value to the model. The specific logic is different depending on the checkbox and the radio. See the code above.

Because the above code is written in the general module of my project Common_angular_ Component.js, so in the call of the general module of the page, the direct use of the Ng-icheck command can achieve ickeck beautification effect, while avoiding a large number of repeated jquery code appearance.

<input type= "Radio" ng-model= "Paomian" value= "Kangshifu" Ng-icheck><input type= "checkbox" Name= "Mantou" Ng-model= "Mantou" Ng-icheck checked>

Reprinted from:

Http://www.storagelab.org.cn/zhangdi/2013/09/09/angularjs%E9%A1%B9%E7%9B%AE%E5%AE%9E%E6%88%98%EF%BC%8103%EF%BC %9aangularjs%e4%b8%8e%e5%85%b6%e4%bb%96%e7%b1%bb%e5%ba%93%e7%9a%84%e5%8d%8f%e4%bd%9c/

ANGULARJS Project actual Combat! 03:ANGULARJS collaboration with other class libraries (GO)

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.