search
HomeWeb Front-endJS TutorialBriefly describe some programming ideas related to AngularJS_AngularJS

In the past few months, I have been traveling in the world of Angular. Looking back now, it's hard to imagine how I would write a large front-end application every day without data binding frameworks like Angular.js, Backbone.js, and their companion Underscore.js. I can't believe I've done that job with them.

Maybe I'm a little biased, but considering that the application I've been working on is a Photoshop-type editor in the browser, it presents the same data in several completely different ways.

  • Layers are presented graphically and occupy most of the screen. They are listed in a panel and you can delete them.
  • When you select a layer, its edges will be surrounded by dotted lines and will be highlighted in the list.
  • Similarly, the dimensions of the layers in the panel and their size properties depend on the canvas.
  • The panels I mentioned above can be dragged, folded, and closed.


Without a framework like Augular, this kind of interaction, data connections, and view synchronization could easily turn into a constant nightmare. Having the ability to fix a local model and fix all related views with Augular sounds almost like a lie. Adding, removing, or altering a level is simply a matter of changing the object. Level, x =10, completed. There is no need to manually invalidate views, manually modify every instance in the DOM hierarchy, or even interact with the DOM for that matter.

Augular allows us to go places we never imagined, like setting up a series of keyboard shortcuts that allow us to make applications in existing environments. For example, file editing shortcuts (like ?B: for toggle bold text) simply enable us to edit a file level.

201562395829701.png (151×117)

Likewise, we attach a description to these shortcuts (registered through a service we created), and then we can display a list of shortcuts, along with their descriptions, in a convenience bar. In addition, we wrote a command that allows us to bind individual DOM elements to their shortcut keys. When your mouse stays on the element for a while, a prompt will appear to let you know the available shortcut keys at that time. .

  • Angular allows us to do things we never dreamed of.

Honestly, it’s like we’re not writing a web application anymore. The web is just a medium. As we improve our understanding of Angular, the code becomes more modular, more self-contained, and more connected and interactive. It naturally becomes more Angular.


And then by Augular, I mean those highly interactive rich application development philosophies behind Augular. JavaScript, a similar thing that allows us to develop parts of software that we thought were impossible some time ago.

201562395953032.png (816×304)

We even have the ability to develop a full-fledged history control panel for modifying the DOM into the currently selected point in history, and make it work very well. It's exciting, to say the least, when you return to the History Dashboard to view data related to Augular's ability to update every tiny detail of your view's work.

That's not always easy, the base code always turns into an uncontrollable mess.

Indeed, over the past few weeks we have been updating and rewriting our entire front-end architecture. Before we start rewriting, let's take a look at the process of updating Angular to its advantage since 0.10.6. If you read the change log, you know this is quite a long process.

In the process of this refactoring, we changed from treating Angular the wrong way to treating Angular the Angular way.

In our case, the wrong approach involved a lot of problems that we had to solve at this point before getting our codebase to a lovely state.

Declare controllers in the global scope

This is an easy example for Angular beginners to do. If you're familiar with Angular, you'll also be familiar with this pattern.

// 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 later
LoginCtrl.$inject = ['$scope', dep1', 'dep2'];

This code is not included in the closure, or in other words, all declarations are in the root scope, the global window object, you bastard. To write in the authentic Angular way, use the module API provided by it. But as you can see, even the documentation and recommended steps are still outdated in recommending that you use global scope:

Do this and great things will happen.

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

    -- Angular.js文档

使用模块(modules)允许我们以下面的方式重写控制器(controllers):
 

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

我发现使用 Angular 控制器的漂亮做法是你必须在所有地方使用控制器方法(controller function),因为你需要控器的依赖注入,而且控制器提供了新的作用域,绑定我们从需求到封装我们所有的脚本文件成为自调用函数表达式( self-invoking function expressions),像这样 (function(){})()。

依赖$injection
在最早的例子中你可能已经注意到了, 依赖是使用$inject注入的. 另一方面,大部份的模块API, 允许你传入一个函数作为参数, 或者一个包含了依赖的数组作为参数, 其后面跟着一个依赖于这些依赖的函数. 这是在Angular中我不喜欢的一点 , 但这应该是它文档的过错. 在文档中的大部份例子认为你并不需要一个数组形式的参数; 但现实是,你是需要的。 如果你在使用一个压缩器压缩你的代码之前, 没有运行ngmin , 事情将会变得糟糕.


由于你没有使用数组格式['$scope',...]明确声明你的依赖包,你看上去简洁的方法参数将会被缩略成类似于b,c,d,e的样子,有效地扼杀了Angular的依赖注入能力。我认为他们构建框架的思路存在了重大的失误,这与我在非常不喜欢 Require.js 和他们麻烦的 AMD 模块最后的推论是相似的。

    如果他不能在产品中使用,它还有什么用?

我的这种态度是因为你在产品中所使用的框架里,有一部分代码是已经写死了的。这对于开发中经常用到、产品中偶尔用到的实用工具,诸如控制台和错误报告,是很好的。如果语法上的甜头(可读性)只用在开发中,就会变得没有任何意义。

这些破事让我很愤怒, 现在发泄完了. 谈谈$符吧...

减少 jQuery扩散

深入的讲, 这个应用是 "类Angular程序", 也就是说它只是包裹于Angular之中, 大多数DOM 交互是经由jQuery处理的, 这给Angular带来相当多的争论。

    如果今天我要从头开始写一款Angular.js应用,我不会立即包含进jQuery。我会强迫自己使用  angular.element 来代替。

如果jQuery存在的话,angular.element这个API将包装它,同时它给Angular团队实现 jQuery的API提供了可以替代的选择,名为jqLite。这并不是说 jQuery不好,或者说我们需要另一个某种实现,来映射它们的API。只是因为使用jQuery显得不是那么有Angular的思想。


让我们来看一个具体的,愚蠢的,例子。在controller被声明的地方,它使用jQuery来做元素之上的类操作。
 

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

然而,我们可以用我们期望的方法来使用Angular,替代之。
 

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

最后一行你不能直接,或者通过jQuery来操作DOM(改变属性,增添事件监听器)。你应该使用指令来替代。那篇文章很棒,去读读看。

如果你仍然jQuery化了,有许多文章可以一读,例如这篇迁移指南,还有我的关于怎样使用jQuery的批判性思考 这篇文章。


我不是要声明我们准备完全移除 jQuery 。我们有其他更重要的目标,例如,发布我们的产品。这个时候,删除 jQuery 的依赖还是很有意义的。这样做能够使我们的控制器得到简化,我们创建处理 DOM 的指令,使用 angular.element 即使它实际上映射着 jQuery 。

我们依赖着有点恶心的 jQuery UI,我们当然不只是为了它的对话框而使用它,它还有很多用途。例如,拖动一个列表项然后把它放到一个已排序的列表中,如果不使用 jQuery UI,这将牵涉到一大堆代码。因此,实际上,对于 jQuery UI 来说,并没有真正很好的替代品。拖拽的功能可以通过一个轻量级的拖拽库 angular-dragon-drop 来替代,但是,对于元素排序插件,还是得依赖 jQuery UI 。

管理代码库

还有一个我们在迁移中需要解决的问题是整个代码库都挤在一个单一的大文件中。这个文件包含了所有控制器、所有服务、所有指令以及每个控制器的特定代码。我指出一点使得我们可以准确地把每个文件只包含一个组件。目前,我们有很少的文件,却包含了不知一个组件。大多数是因为一个指令使用一个服务来与外界共享数据。

尽管和 Angular 无关,我们还是把我们的 CSS 样式表(stylesheet)模块化。我们为每个组件中使用的 CSS 类名前面都加上了两个字的前缀。例如, .pn- 作为前缀,代表面板(panel); .ly- 前缀,代表着图层(layer)等等。这样做的直接好处就是,你不需要再费劲地想哪个组件的 CSS 类是怎样的了。因为你已经为它们设置了命名空间,你就很少会重复用到某一个 CSS 类名了。另一个好处就是减少了嵌套,我们以前曾经用 #layoutEditor div.layer .handle div 这样复杂的选择器表达式,而现在,我们只需要 .ly-handle-content 就可以了。深度的嵌套现在只发生在额外的选择器覆盖上,例如 .foobar[disabled]:hover,或者,最坏的情况下,像 .foo-bar .br-baz 。


下面是一些我们定下的 CSS 类命名规则:

  •     用两个字符来描述组件名:.ly-、.dd-、.dg-等等
  •     采用 .ly-foo-barname 来代替嵌套命名 .ly-foo .bar
  •     避免内联样式,总是使用 CSS 类名。这能够减少不界面的一致性,提高语义解释能力
  •     不要在 CSS 中使用 ID 来赋值

在实现了这套面向组件的 CSS 声明方法后,我又想了很久“the class soup way”。

Angular 强制你写好的代码,但是更深一层说,它强制你去思考。一会儿后,它就像一个服务器端的实现,或者成为一个不堪忍受的“黑客大会”。这些都取决于你这么选择。

接近完美

让我们来解析一下我们应用程序的各部件的其中之一,层。

div.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, which means that this element is part of the canvas component (canvas refers to the place where we draw the layer, not to be confused with HTML5 canvas). Then, we use the ngRepeat tag in a foreach-like loop to create a similar element for each layer. And passed through a reverse filter we wrote, so the last layer is on top and visible to the user. The apLayer tag is actually used for the task of drawing a layer, whether it is a picture, some text, HTML, or something else. The event tags (ng-mousedown, ng-mouseup, ng-dblclick) are simply used as proxies for events that will be handled by our layer selection service. Finally, I think there is no need to say more about the ngHide tag.


There are so many functions (Translator's Note: It's a bit exaggerated), and Angular has succeeded in making it look so simple, using readable HTML to tell you what they are about to a certain extent. More importantly, it allows you to break down different issues to consider so that you can write concise code without having to consider everything at once. In short, it reduces complexity (Translator's Note: Angular itself is actually very complex, haha) and makes complexity simple. And make "problems that are difficult to easily measure" possible.

I look forward to more articles about Angular coding soon. In particular, I enjoy exploring some of the edge cases I encounter when upgrading my code and how to fix them while making the rest of the code work the same.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
2022年最新5款的angularjs教程从入门到精通2022年最新5款的angularjs教程从入门到精通Jun 15, 2017 pm 05:50 PM

Javascript 是一个非常有个性的语言. 无论是从代码的组织, 还是代码的编程范式, 还是面向对象理论都独具一格. 而很早就在争论的Javascript 是不是面向对象语言这个问题, 显然已有答案. 但是, 即使 Javascript 叱咤风云二十年, 如果想要看懂 jQuery, Angularjs, 甚至是 React 等流行框架, 观看《黑马云课堂JavaScript 高级框架设计视频教程》就对了。

使用PHP和AngularJS搭建一个响应式网站,提供优质的用户体验使用PHP和AngularJS搭建一个响应式网站,提供优质的用户体验Jun 27, 2023 pm 07:37 PM

在如今信息时代,网站已经成为人们获取信息和交流的重要工具。一个响应式的网站能够适应各种设备,为用户提供优质的体验,成为了现代网站开发的热点。本篇文章将介绍如何使用PHP和AngularJS搭建一个响应式网站,从而提供优质的用户体验。PHP介绍PHP是一种开源的服务器端编程语言,非常适用于Web开发。PHP具有很多优点,如易于学习、跨平台、丰富的工具库、开发效

使用PHP和AngularJS构建Web应用使用PHP和AngularJS构建Web应用May 27, 2023 pm 08:10 PM

随着互联网的不断发展,Web应用已成为企业信息化建设的重要组成部分,也是现代化工作的必要手段。为了使Web应用能够便于开发、维护和扩展,开发人员需要选择适合自己开发需求的技术框架和编程语言。PHP和AngularJS是两种非常流行的Web开发技术,它们分别是服务器端和客户端的解决方案,通过结合使用可以大大提高Web应用的开发效率和使用体验。PHP的优势PHP

使用PHP和AngularJS开发一个在线文件管理平台,方便文件管理使用PHP和AngularJS开发一个在线文件管理平台,方便文件管理Jun 27, 2023 pm 01:34 PM

随着互联网的普及,越来越多的人在使用网络进行文件传输和共享。然而,由于各种原因,使用传统的FTP等方式进行文件管理无法满足现代用户的需求。因此,建立一个易用、高效、安全的在线文件管理平台已成为了一种趋势。本文介绍的在线文件管理平台,基于PHP和AngularJS,能够方便地进行文件上传、下载、编辑、删除等操作,并且提供了一系列强大的功能,例如文件共享、搜索、

如何在PHP编程中使用AngularJS?如何在PHP编程中使用AngularJS?Jun 12, 2023 am 09:40 AM

随着Web应用程序的普及,前端框架AngularJS变得越来越受欢迎。AngularJS是一个由Google开发的JavaScript框架,它可以帮助你构建具有动态Web应用程序功能的Web应用程序。另一方面,对于后端编程,PHP是非常受欢迎的编程语言。如果您正在使用PHP进行服务器端编程,那么结合AngularJS使用PHP将可以为您的网站带来更多的动态效

使用Flask和AngularJS构建单页Web应用程序使用Flask和AngularJS构建单页Web应用程序Jun 17, 2023 am 08:49 AM

随着Web技术的飞速发展,单页Web应用程序(SinglePageApplication,SPA)已经成为一种越来越流行的Web应用程序模型。相比于传统的多页Web应用程序,SPA的最大优势在于用户感受更加流畅,同时服务器端的计算压力也大幅减少。在本文中,我们将介绍如何使用Flask和AngularJS构建一个简单的SPA。Flask是一款轻量级的Py

AngularJS基础入门介绍AngularJS基础入门介绍Apr 21, 2018 am 10:37 AM

这篇文章介绍的内容是关于AngularJS基础入门介绍,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下。

如何使用PHP和AngularJS进行前端开发如何使用PHP和AngularJS进行前端开发May 11, 2023 pm 05:18 PM

随着互联网的普及和发展,前端开发已变得越来越重要。作为前端开发人员,我们需要了解并掌握各种开发工具和技术。其中,PHP和AngularJS是两种非常有用和流行的工具。在本文中,我们将介绍如何使用这两种工具进行前端开发。一、PHP介绍PHP是一种流行的开源服务器端脚本语言,它适用于Web开发,可以在Web服务器和各种操作系统上运行。PHP的优点是简单、快速、便

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),