This article describes the AngularJS encapsulation instruction method. Share it for your reference, as follows:
Introduction: angularjs is a medium-heavyweight front-end development framework
HTML is a good language designed for static text, but it will be weak to build dynamic web applications. Generally, we use the following techniques to solve the shortcomings of static web technology in building dynamic applications:
1. Class library: Class library is a collection of a class of functions that can help you write web applications. The leading role here is your code, and it is up to you to decide when to use the class library. Typical class libraries, such as prototype, jQuery, etc.
2. Framework: A framework-based special, implemented web application, you only need to fill in specific business logic. The framework plays a leading role here, and it calls your code based on specific logic. Typical frameworks such as knockout, sproutcore, YUI, etc. AngularJS is one of them.
The frame is also divided into severity. My criterion for judging severity is whether there are many third-party libraries needed to help you implement functions. Obviously, backbone is a lightweight framework. It is simple and easy to use and focuses on the implementation of front-end MVC. Therefore, you still need a lot of third-party library (at least jquery) to complete various contents such as dom operations, UI, etc. Yui and dojo are heavy frameworks. Their authors attempt to create a versatile framework + component library, including dynamic code calls and various UI components, which are relatively expensive to learn, but once they are proficient, at least there is nothing else to ask for in this project. From this perspective, a lightweight frame is like a rough house, which requires various tools to decorate, but it is also more flexible for developers. A heavyweight frame is like a well-decorated room. All you need is to adapt to it, but if you want to make drastic changes yourself, it will be a little bit of a traumatic injury.
angularjs, in my opinion, is between the above two categories and is a medium-heavyweight framework. That is, it is not as simple as backbone, nor is it as all-encompassing as dojo and Yui. Many times, if you want to be all-inclusive, many submodules often have high quality and are more difficult to modify. If the framework is too thin, too much content needs to be written. Angularjs, a relatively modest style, is very suitable for my needs. At present, the three most exquisite components of AngularJS are data binding (Scope), directive (Directive) and dependency injection (Dependency Injection), which perform very well. Relatively speaking, its UI components and animations are weaknesses. It can be said that choosing angularjs means choosing a jquery-style component library method to make up for its shortcomings. To complete a web application, you must deal with third-party class libraries.
There are many UI plug-ins written for angularjs, some of which combine bootstrap and some of which combine jquery. Although they are not perfect, they are all worth referring to:/
Collaboration with jquery class library
In the third-party library, we have to mention the famous jquery, which is now basically a compulsory tool for domestic web development. Its flexible dom operation makes many web developers unable to stop. Coupled with the already mature jquery UI library and a large number of jquery plug-ins, it is almost an inexhaustible treasure house. However, can it be combined with angularjs?
Many angularjs fundamentalists are negative about this. They believe that since angularjs has been used as the web application framework, it is necessary to avoid interference from other class libraries and make pure MvvM mode applications. Any dom operation similar to jquery is unclean. Put all interface-related operations, such as dom operations, in directive, so that the page is directive without code, which is consistent with JSF's idea. MVVM, DSL, componentization ideas are the trend of the web. Well, the idea is good, fundamentalists are so pure. But the fact is that when we use angularjs, we cannot do without jquery.
As we all know, jquery lite. is actually built into angularjs, and many methods in the angularjs source code are directly used to use jquery methods. For example, the event binding mechanism of angularjs. Since the prophets are all using it, why don’t we use it? There is nothing wrong with the idea of componentization, but there is no need to tie your hands and feet because of this. The only thing to note is not to use jquery's code to destroy the structure of angularjs. My principles for this are as follows. Please point out the shortcomings:
In important aspects such as module division, services, routing, and dependency injection, angularjs must be used. Only certain specific content (usually some Ui) can be used. Avoid writing a bunch of jquery codes in the controller that directly manipulate dom elements. Use angularjs' template binding mechanism. Commonly used components need to be extracted using the angularjs method, but the specific implementation of components does not have to worry about whether to use jquery and its plug-ins. .When using third-party class libraries, there are special marks when naming variables and functions (usually with the abbreviation of this class library name).
jquery, it is even more recommended that as an angularjs dependency, it will be loaded in before angularjs.
In fact, choosing a framework like angularjs Chinese and German mid-heavyweight player means you have to add other class libraries. And jquery is even more recommended as an angularjs dependency, loading in before angularjs. Because when looking at the angularjs API, I have found that many of these features are actually dependent on jquery. A typical example is the ng-blur instruction on the official website.
<input type="text" ng-model="name" ng-blur="checkname()" > The ng-blur directive is a command that is triggered when the focus leaves an element. For the above example, when the focus leaves the text input box, the checkname() function is triggered.
It looks simple, but if you really use this command, you will find that it has no effect at all. After a closer look at the documentation, I realized that this was actually a function implemented by the prophets using jquery's blur method (and in fact it was not really implemented and placed in the current version). Then even if we want to write one, it is not possible to leave the jquery native library, because the blur method is not encapsulated into the jquery lite brought in angularjs. In other words, the complete jquery must be loaded before it can be used. So, I simply wrote a tag myself:
/* * angular directive onBlur * * @description my ng-blur * @require jquery */ $('onBlur', function() { return { restrict : 'A', link : function(scope, elm, attrs) { ('blur', function() { scope.$apply(); }); } }; });
This is already very good.
But it's not perfect. Due to the problem that the $apply method accepts functions, writing directly like the above may cause an angularjs runtime error: $apply already in progress
To avoid this problem, you need to process the $apply method:
/* factory function safeApply * * @description If you find yourself triggering the '$apply already in progress' error while developing with * (for me I find I hit most often when integrating third party plugins that trigger a lot of DOM events), * you can use a 'safeApply' method that checks the current phase before executing your function. * * @param scope, the action scope, mostly is the topmost controller * @param fn, the function which you want to apply into scope * @see /p/ngisma */.factory('safeApply', function($rootScope) { return function(scope, fn) { var phase = scope.$root.$$phase; if (phase == '$apply' || phase == '$digest') { if (fn && ( typeof (fn) === 'function')) { fn(); } } else { scope.$apply(fn); } } });
Then the previous onblur tag should be changed to:
/* * angular directive onBlur * * @description my ng-blur * @require jquery */ $('onBlur', function(safeApply) { return { restrict : 'A', link : function(scope, elm, attrs) { ('blur', function() { safeApply(scope, ); }); } }; });
I have added my own angular_extend module to my own project and used it, and it works very well.
Example of encapsulating jquery plug-in into components in angularjs
icheck is a jquery plugin for beautifying Checkbox and Radio buttons across browsers. About its introduction, in /p/icheck/
Generally speaking, its usage is to add a piece of jquery code after dom is loaded:
$('input').iCheck({ labelHover : false, cursor : true, checkboxClass : 'icheckbox_square-blue', radioClass : 'iradio_square-blue', increaseArea : '20%' });
However, since we want to put it in our project, we cannot stuff this jquery code that directly operates dom everywhere, which is neither beautiful nor easy to maintain. According to the principles mentioned before, it is best to encapsulate it into an angular instruction pattern and place it in a public module to call it. Here I named my newly created command ng-icheck. In this way, we just need to write a checkbox or radio html tag to add a ng-ickkeck. The specific implementation is as follows:
/* * angular directive ng-icheck * * @description icheck is a plugin of jquery for beautifying checkbox & radio, now I complied it with angular directive * @require jquery, icheck * @example <input type="radio" ng-model="paomian" value="kangshifu" ng-icheck> * <input type="checkbox" class="icheckbox" name="mantou" ng-model="mantou" ng-icheck checked> */ $('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 ($ == "checkbox") { //checkbox, $ViewValue = true/false/undefined $scope.$apply(function() { $ngModel.$setViewValue(!($ngModel.$modelValue == undefined ? false : $ngModel.$modelValue)); }); } else { // radio, $ViewValue = $ $scope.$apply(function() { $ngModel.$setViewValue($); }); } }); }, }; });
It is worth noting in the above code: after using the icheck plug-in, a beautified div will be generated and overlaid on the original checkbox or radio, and the original checkbox or radio will be hidden. Therefore, when we click on them, we will not directly contact the event, causing the model value bound to checkbox or radio to change. So we need to rebind the event here, use
$ngModel.$setViewValue() method to assign value to the model. The specific logic varies according to checkbox and radio. See the above code for details.
Since the above code is written in the common_angular_component.js of the general module in my project, on the page where the general module is called, the ng-icheck directive can be used to achieve the beautification effect of ickeck, while avoiding the occurrence of a large number of duplicate jquery code.
For more information about AngularJS, readers who are interested in view the topic of this site:AngularJS Introduction and Advanced Tutorial"and"AngularJS MVC architecture summary》
I hope this article will be helpful to everyone's AngularJS programming.