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

Source: Internet
Author: User

Introduction: Angularjs is a medium-weight, front-end development framework

HTML is a good language for static text design, but it is weak to build a dynamic Web application. In general, we use the following techniques to solve the disadvantages of static web page technology in building dynamic applications:

1. Class Library: A class library is a collection of functions that can help you write Web applications. The dominant role here is your code, which you decide when to use the class library. Typical class libraries, such as prototype, jquery, and so on.

2. Framework: A special, implemented Web application that you only need to populate with specific business logic. The framework here is the dominant one, and it calls your code according to the specific logic. Typical frameworks such as Knockout,sproutcore, Yui and so on. Angularjs is one of them.

The framework also has the weight of the points. My judgment on severity is whether there is a need for a lot of third-party libraries to help you implement functionality. Obviously, backbone is a lightweight framework that is easy to use and focused on the implementation of front-end MVC, so you need a lot of third-party libraries (at least jquery) to do a variety of things like DOM manipulation, UI, and so on. Yui, Dojo is a heavy frame, their authors try to develop a Vientiane Framework + component library, including code dynamic calls, a variety of UI components are included, learning costs are high, but once proficient, at least the project has nothing to ask for. From this point of view, the lightweight frame is like a blank room and requires a variety of tools to decorate it, but it is also more flexible for developers. The heavyweight frame is like a well-decorated room, you just need to adapt to it, but if you want to make a drastic change, it is a little bit hurt by the bone.

Angularjs, in my opinion, is a medium-weight framework between the two categories. 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:

Angularjs is used in the important aspects of module partitioning, service, routing, Dependency injection, and only some specific content (usually some UI) uses jquery. Avoid writing a bunch of jquery code that directly manipulate DOM elements in the controller. Use the Angularjs template binding mechanism. 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. When using a third-party class library, there are special tags (usually the abbreviation for the class library name) when the variables and functions are named.

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 ()" 〉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:

 /* * angular directive onBlur * * @description my ng-blur * @require jquery * *$compileProvider.Directive(' OnBlur ', function() {return {Restrict: ' A ',Link: function(Scope,Elm,Attrs) {Elm.Bind(' Blur ', 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  While developing with angular.js * (for me I find I hits most often when integrating third party plugins that trigger a lot of 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&& ( typeof (fn) === ' function ')) {fn();}} Else {Scope.$apply(fn);}}});

Then the previous onblur label should read:

 /* * angular directive onBlur * * @description my ng-blur * @require jquery * *$compileProvider.Directive(' OnBlur ', function(safeapply) {return {Restrict: ' A ',Link: function(Scope,Elm,Attrs) {Elm.Bind(' Blur ', 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    Labelhover  :    false    cursor  :    true    Checkboxclass  :     Icheckbox_ Square-blue '    Radioclass  :  Span class= "PLN" >   ' iradio_square-blue '    Increasearea  :     ' 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 are a plugin of jquery for beautifying checkbox & Radio, n ow I complied it with angular directive * @require jquery, Icheck * @example <input type= "Radio" ng-model= "Paomian" Val Ue= "Kangshifu" ng-icheck> * <input type= "checkbox" class= "Icheckbox" name= "Mantou" ng-model= "Mantou" Ng-ich Eck Checked> * /$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.


Source: Http://community.angular.cn/A0fG



Null

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

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.