Explanation of AngularJS encapsulation commands and angularjs Encapsulation
This article describes the AngularJS command encapsulation method. We will share this with you for your reference. The details are as follows:
Introduction: angularjs is a moderately important front-end development framework.
HTML is a good language designed for static text, but it is obviously weak to build dynamic web applications. Generally, the following technologies are used to solve the shortcomings of static Web pages in building dynamic applications:
1. Class Library: A class library is a set of functions that can help you write web applications. The dominant role here is your code. It is up to you to decide when to use the class library. Typical class libraries, such as prototype and jQuery.
2. Framework: frame a special and implemented web application. You only need to fill in the specific business logic. Here, the framework plays a leading role in calling your code according to the specific logic. Typical frameworks include knockout, sproutcore, and YUI. AngularJS is also one of them.
The framework is equally important. My judgment on the importance is whether many third-party libraries are required to help you implement functions. Obviously, backbone is a lightweight framework that is easy to use and focuses on the implementation of front-end Mvc. Therefore, you need many third-party class libraries (at least jquery) to complete dom operations, UI, and other content. Yui and dojo are heavy-duty frameworks. Their authors attempted to create a senluowanxiang framework + component library, including dynamic code calling and various UI components, with high learning costs, but once proficient, at least this project has nothing to do. From this perspective, the Lightweight Framework is like a rough room and requires various tools for decoration, but it is more flexible for developers. The heavyweight framework is like a well-decorated room. You only need to adapt to it, but if you want to make drastic changes on your own, it will slightly hurt your bones.
Angularjs, in my opinion, is a medium heavyweight framework between the above two classes. That is, it is not as simple as backbone, nor is it as all-encompassing as dojo and Yui. In many cases, the quality of many sub-modules is too low and difficult to modify. If it is too short, too much content needs to be written in the thin frame content. Angularjs, a relatively moderate style, is very suitable for my needs. Currently, AngularJS's three most sophisticated components, I think, are Scope, Directive, and Dependency Injection. Relatively speaking, its UI components and animations are weaknesses. It can be said that the choice of angularjs means that the jquery component library method is used to make up for its shortcomings. To complete a web application, you must deal with a third-party class library.
Now there are many UI plug-ins written for angularjs, some combined with bootstrap, some combined with jquery, although not perfect, are very worthy of reference: http://angular-ui.github.io/
Collaboration with jquery Class Libraries
Among the third-party class libraries, I have to mention the famous jquery, which is now basically a required tool for web development in China. Its flexible dom operations make it hard for many web developers to stop. Coupled with the already mature jquery UI library and a large number of jquery plug-ins, it is almost an Inexhaustible Treasure. However, can it be combined with angularjs?
Many angularjs starters have a negative attitude towards this. They believe that since angularjs has been used as a web application framework, it is necessary to avoid interference from other class libraries and implement pure MvvM mode applications. Any dom operations similar to jquery are unclean. Put all interface-related operations, such as dom operations, in directive, so that there is no code for direve VE on the page, which is consistent with the JSF idea. MVVM, DSL, and componentization are web Trends. Well, the idea is very good, and the ideas of the original Enis are so pure. But the fact is that we can't leave jquery without angularjs.
As we all know, jquery lite is already built in angularjs, and many methods in angularjs Source Code directly use the jquery method. For example, angularjs event binding mechanism. Since the Prophets are using it, why don't we bother? The idea of componentization is correct, but it is not necessary to tie your hands and feet. The only problem to be aware of is that do not use jquery code to break the angularjs structure. My principles are as follows:
Angularjs is used for module division, service, routing, dependency injection, and other important aspects. jquery is used only for some specific content (usually some UIS. Avoid writing a bunch of jquery Code that directly operates dom elements in the controller. Use angularjs's template binding mechanism. Commonly used components are extracted using angularjs, but the specific implementation of components does not have to worry about whether jquery and its plug-ins are used. When using a third-party class library, there are special marks when naming variables and functions (usually the abbreviation of this class library name ).
Jquery is also recommended as the dependency of angularjs, which is loaded before angularjs.
In fact, if you select a framework such as angularjs, you must add other class libraries. Jquery, in addition, is recommended as the dependency of angularjs, which is loaded before angularjs. Because when viewing angularjs APIs, I have discovered that many of these functions are actually dependent on jquery. A typical example is the ng-blur command on the official website.
<Input type = "text" ng-model = "name" ng-blur = "checkname ()"> the ng-blur command is triggered when the focus leaves an element. In the previous example, when the focus leaves the text input box, the checkname () function is triggered.
It looks simple, but if you use this command, you will find that it doesn't work at all. After carefully reading the document, I found that this is actually a function implemented by the Xianzhi using jquery's blur method (and in fact it is not actually implemented and put in the current version ). Even if we want to write one, it won't work if we leave the jquery native library, because the blur method is not encapsulated in the jquery lite in angularjs. In other words, you must load the complete jquery before using it. 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); }); } };});
This is already good.
But not perfect. Because the $ apply method accepts functions, writing like above may cause angularjs to run and report an 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 Angular.JS* (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 https://coderwall.com/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); } }});
The previous onblur tag should be changed:
/** 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); }); } };});
I have added my angular_extend module to the above Code and used it in my own project. The result is very good.
Example of encapsulating jquery plug-in into components using angularjs
Icheck is a jquery plug-in used to beautify Checkbox and Radio buttons across browsers. About it, In http://www.bootcss.com/p/icheck/
In general, it is used by adding a piece of jquery code after dom loading:
$('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 plug this jquery Code that directly operates the dom everywhere, which is neither beautiful nor easy to maintain. According to the principle mentioned earlier, it is best to encapsulate it into the angular instruction mode and put it in the public module for calling. Here I name the new command ng-icheck. In this case, add ng-ickeck to the html Tag of a checkbox or radio. 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> */$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 the icheck plug-in is used, a beautifying div will be generated to overwrite the original checkbox or radio, the original checkbox or radio will be shadow. Therefore, when we click them, the event will not be directly triggered, so that the model value bound to the checkbox or radio changes. So here we need to re-bind the event and use
$ NgModel. $ setViewValue () method to assign values to the model. The specific logic varies depending on checkbox and radio. For more information, see the above Code.
The above code is written in common_angular_component.js, a general module in my project. Therefore, on the page that calls this general module, you can directly use the ng-icheck command to beautify the ickeck, at the same time, the emergence of a large number of repeated jquery code is avoided.