Briefly describe some programming ideas related to AngularJS _ AngularJS

Source: Internet
Author: User
This article mainly introduces some programming ideas related to AngularJS. AngularJS is a popular JavaScript library and is recommended! For more information, see how I have been traveling in Angular over the past few months. In retrospect, it is hard to imagine how to write a large front-end application every day without the data binding frameworks like Angular. js, Backbone. js, and its partner Underscore. js. I can't believe I have used them to complete the job.

I may be a little biased, but considering that the app I 've been working on is implementing a Photoshop-type editor in a browser, there are several completely different ways to present the same data.

  • Layers are displayed in a graphical form, occupying most of the screen. They are listed in a panel and you can delete them.
  • When you select a layer, its edge is surrounded by dotted lines and highlighted in the list.
  • Similarly, the size and size of layers in the panel depend on the canvas.
  • The Panel I mentioned above can be dragged, folded, or closed.


If it is not a framework like Augular, interactions, data connections, and view synchronization of this type can easily become a persistent nightmare. Having the ability to correct models in one place and using Augular to correct all relevant views sounds almost like a lie. Adding, removing, or modifying a hierarchy is just a matter of changing objects. Level, x + = 10, complete. There is no need to manually invalidate the view, manually modify every instance in the DOM hierarchy, or even interact with the DOM because of this problem.

Augular allows us to go to a place we never thought about, just like setting a keyboard shortcut that allows us to make an application in an existing environment. For example, file editing shortcuts (like? B: used to switch the text) only enables us to edit a file layer.

Similarly, We append a description for these shortcut keys (registered through a service we created). Then we can display a list of shortcut keys and their descriptions, on a convenience bar. In addition, we have written a command to bind separate DOM elements with their shortcut keys. When you move your mouse over the elements for a while, a prompt will appear, let you know the shortcut keys available at this time.

  • Angular enables us to do things we never dreamed.

To be honest, it seems that we are not writing a web application. Web is just a media. When we enhance our understanding of Angular, the Code becomes more modular, independent, and interactive. It naturally becomes more Angular.


Then, through Augular, I mean the rich application development philosophy that is highly interactive behind Augular. Javascript, a similar thing that allows us to develop a piece of software that we thought was not possible a while ago.

We even have the ability to develop a mature history control panel for modifying the DOM to the currently selected point in history and make it work well. At least that can be said, when you are excited to return to the history console to view data related to Augular capabilities, you can perfectly update every tiny detail in your view work.

It is not always easy. The basic code is always an uncontrollable mess.

Indeed, we have been updating and rewriting the entire front-end architecture over the past few weeks. Before rewriting, let's take a look at the process of updating Angular with advantages since 0.10.6. If you read the change log, you will know that this is a very long process.

In This refactoring process, we have changed from treating Angular in the wrong way to Angular in the way.

In our case, the incorrect method involves many problems, and we have to solve them before we make our code base reach the cute state.

Declare controller (Controllers) IN GLOBAL SCOPE)

This is an example that Angular beginners can easily make. If you are familiar with Angular, you will also be familiar with this mode.

// winds up on window.LoginCtrl ...var LoginCtrl = function ($scope, dep1, dep2) {  // scope defaults}; LoginCtrl.prototype.resetPassword = function () {  // reset password button click handler }; // more on this one laterLoginCtrl.$inject = ['$scope', dep1', 'dep2'];

This code is not included in the closure, or all declarations are in the root scope, global window object, asshole. The module api provided by Angular is used ). As you can see, we recommend that you use the global scope even if the document and recommendation steps are outdated:

In this way, great things will happen.

  // A Controller for your app  var XmplController = function($scope, greeter, user) {   $scope.greeting = greeter.greet(user.name);  }

-- Angular. js document

Using modules allows us to override controllers in the following ways ):

angular.module('myApp').controller('loginCtrl', [  '$scope', 'dep1', 'dep2',  function ($scope, dep1, dep2) {    'use strict';     // scope defaults     $scope.resetPassword = function () {      // reset password button click handler    };  }]);

I found that the nice way to use Angular controllers is to use the controller function in all places, because you need to inject the controller dependency and the controller provides a new scope, bind all of our script files from requirement to encapsulation to self-called function expressions (self-invoking function expressions), like this (function (){})().

Dependency $ injection
In the earliest example, you may have noticed that the dependency is injected with $ inject. on the other hand, most module APIs allow you to input a function as a parameter, or an array containing dependencies as a parameter, followed by a function dependent on these dependencies. this is something I do not like in Angular, but it should be the fault of its documentation. in most examples of this document, you do not need an array parameter, but the reality is that you need it. If you do not run ngmin before compressing your code with a compressed file, the process will become worse.


Because you have not used the array format ['$ scope',...] explicitly declare your dependency package. The simple method parameters will be reduced to B, c, d, and e, effectively killing Angular dependency injection capabilities. I think there are major mistakes in their ideas for building the framework, which is similar to the final inference of the AMD module that I do not like Require. js very much and they have troubles.

If it cannot be used in the product, what is its use?

My attitude is that some of the Code in the framework you use in the product has been written to death. This is good for practical tools that are frequently used in development and occasionally used in products, such as the console and error reports. If the syntactic sweetness (readability) is only used in development, it will become meaningless.

I am very angry with these things. Now I have vented my anger. Let's talk about $ fu...

Reduce jQuery Diffusion

In depth, this application is a "Angular-like program", that is, it is wrapped in Angular, and most DOM interactions are processed by jQuery, which brings a lot of debate to Angular.

If I want to write an Angular. js application from scratch today, I will not include it in jQuery immediately. I will force myself to use angular. element instead.

If jQuery exists, the angular. element API will encapsulate it, and it provides an alternative option for the Angular team to implement jQuery APIs, called jqLite. This does not mean that jQuery is not good, or we need another implementation to map their APIs. It is because jQuery is not so Angular-oriented.


Let's look at a specific, stupid example. Where the controller is declared, it uses jQuery to perform class operations on elements.

p.foo(ng-controller='fooCtrl') angular.module('foo').controller('fooCtrl', function ($scope) {  $('.foo').addClass('foo-init');   $scope.$watch('something', function () {    $('.foo').toggleClass('foo-something-else');  });});

However, we can replace Angular with the method we expect.

angular.module('foo').controller('fooCtrl', function ($scope, $element) {  $element.addClass('foo-init');   $scope.$watch('something', function () {    $element.toggleClass('foo-something-else');  });});

You cannot operate the DOM directly on the last line, or use jQuery (changing attributes and adding Event Listeners ). You should use commands instead. That article is great. Read it.

If you are still using jQuery, you can read many articles, such as this migration guide and my critical thoughts on how to use jQuery.


I am not trying to declare that we are preparing to completely remove jQuery. We have other more important goals, such as releasing our products. At this time, it makes sense to delete jQuery dependencies. In this way, our controller can be simplified. We create DOM-processing commands and use angular. element even if it is actually mapped to jQuery.

We rely on jQuery UI, which is a bit disgusting. Of course we don't just use it for its dialog box, but it also has a lot of usage. For example, drag a list item and place it in a sorted list. If jQuery UI is not used, this involves a lot of code. Therefore, in fact, there is no really good alternative for jQuery UI. The drag-and-drop function can be replaced by a lightweight drag-and-drop library angular-dragon-drop. However, the element sorting plug-in still needs to rely on jQuery UI.

Manage code Libraries

Another problem we need to solve during migration is that the entire code library is crowded into a single large file. This file contains all controllers, all services, all commands, and specific code for each controller. I pointed out that each file can contain only one component accurately. At present, we have very few files, but we do not know a component. Most of the reasons are that a command uses a service to share data with the outside world.

Although it has nothing to do with Angular, we still modularize our CSS style sheet (stylesheet. We add a prefix of two words to the CSS class name used in each component. For example,. pn-is the prefix, indicating panel;. ly-prefix, indicating layer. The direct advantage of this is that you don't need to think about which component's CSS class is like any more. Because you have already set namespaces for them, you will rarely reuse a CSS class name. Another benefit is reduced nesting. We used to use # layoutEditor p. layer. handle p is a complex selector expression. Now, we only need. ly-handle-content. Deep nesting now only happens with extra selector overwrites, such as. foobar [disabled]: hover, or, in the worst case, like. foo-bar. br-baz.


The following are some CSS naming rules:

  • Use two characters to describe the component name:. ly-,. dd-,. dg-, and so on.
  • Use. ly-foo-barname instead of nested name. ly-foo. bar
  • Avoid inline styles and always use CSS class names. This reduces non-interface consistency and improves semantic interpretation.
  • Do not assign values by ID in CSS.

After implementing this component-oriented CSS declaration method, I thought for a long time "the class soup way ".

Angular forces you to write the code, but at a deeper level, it forces you to think. After a while, it is like a server-side implementation, or an unbearable "Hacker Conference ". These are all dependent on your choice.

Near perfection

Let's analyze one of the components of our application, layer.

p.cv-layer(  ng-repeat="layer in page.layers | reverse",  ap-layer,  ng-mousedown="selectLayer(layer.id)",  ng-mouseup="selectLayer(layer.id)",  ng-dblclick="doubleClickLayer(layer)",  ng-hide="layer.invisible")

Here, we use the cv-layer class, that is to say, this element is part of the canvas component (canvas refers to the place where we draw the layer and should not be confused with HTML5canvas ). Then, we use the ngRepeat label in a loop similar to foreach to create a similar element for each layer. It is passed through a Reverse filter we have written. Therefore, the last layer is located at the top and visible to users. The apLayer tag is used to draw layer tasks, whether it is an image or some text, HTML, or something else. The event tag (ng-mousedown, ng-mouseup, ng-dblclick) is simply used as a proxy for the event, and these events will be processed by our layer selection service. Finally, I don't need to talk about the ngHide label.


So many features (Translator's note: a little exaggerated), and Angular successfully makes it look so simple, with readable HTML, it tells you to some extent what they are. More importantly, it allows you to break down different issues that need to be considered, so that you can write simple code without taking all the things into consideration at once. In short, it reduces the complexity (in fact, Angular itself is very complicated, huh, huh) and makes complexity easier. This makes the problem of "difficult to measure easily" possible.

I look forward to coming soon

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.