search
HomeWeb Front-endJS TutorialIn-depth analysis of Angularjs1 component programming (with examples included)

This article mainly introduces the in-depth analysis of angularjs1. Don’t find it difficult. As long as you don’t find it difficult, then you can learn angularjs here. This is a test for everyone. article, let us take a look at this article now

angular 1 We must also component-oriented programming

Front-end componentization is an irreversible trend in the front-end development model. The three main front-end Framework angular 2 react vue all regard component programming as one of their major selling points, angular 1 as a framework with a relatively long history The framework, driven by the illegitimate son angular 2, has finally caught up with the last train of component-based programming. Those old projects in the company finally have the opportunity to experience the taste of component-based programming.

The road to componentization in angular 1

angular 1 Programming ideas similar to componentization have actually been around for a long time, but they were not called components at that time. Directive, after specifying restrict: 'E', this directive is very similar to the usage of today's components. In angular 1.5, the instructions were restricted based on similar concepts in angular 2, and were reborn into today's components.

Features of components

The official documentation lists the differences between components and instructions. In addition, a standard component should also meet the following characteristics.

  1. The label name of the component must contain a hyphen

  2. The component has a good life cycle

  3. Components are self-contained

  4. Components are self-enclosed

  5. Components are reusable

  6. Components can be customized

The following are explained in sequence.

Name specifications for components

Unlike directives, components must be an element, and HTML has special specifications for this.

The HTML specification leaves tags with underscores for developers to use. The elements formed in this way are also called custom elements. Although we have not used the concept of custom elements, the behavior of the two is similar. We should meet this standard.

This specification corresponds to angular 1: the component name must be in camel case.

For example:

module.component('dialog', {
    // ...
});

This is not right. The HTML specification has defined the standard element dialog. Reusing tag names may cause our custom component behavior to be mixed with the behavior of the standard element, leading to weird bugs; and if this is done, it will also indirectly prevent developers from using the native dialog tag.

In addition, even if a certain element is not defined in the current standard, it does not mean that it will not be defined in the future. Since our program runs in the browser, it must follow the rules. This is a legal way of writing:

module.component('customDialog', {
    // ...
});

Self-containedness of components

A well-designed component must have its own behavior and default style.

Default behavior

The default behavior is defined with the controller (Controller) in angular 1.

function CustomDialogController($service) {
    this.someField = 123;
    this.someMethod = function someMethod() {

    }
}
CustomDialogController.$inject = ['$service'];

module.component('customDialog', {
    controller: CustomDialogController,
    template: require('./customDialogTemplate.html'),
});

Because the component enables controllerAs by default, all variables and functions are bound to this, so you can also use ES2015 The class syntax to organize the code:

class CustomDialogController {
    constructor($service) {

    }

    someMethod() {

    }
}
CustomDialogController.$inject = ['$service'];

module.component('customDialog', {
    controller: CustomDialogController,
    template: require('./customDialogTemplate.html'),
});

One problem with this is that other functions cannot use the service (Service) injected in constructor, and can only use this One transfer. My personal approach is as follows:

class CustomDialogController {
    constructor($service) {
        this.services = { $service };
    }

    someMethod() {
        const { $service } = this.services;
    }
}
// 下略

It is recommended that controllers of components with relatively simple logic be defined using function, and complex components should be defined using class, with the latter code The levels should be clearer and easier to read.

Default style

The default style of the component is specified directly using the style sheet.

custom-dialog {
    display: block;
    // ...
}

For all tags that the browser does not recognize, the default is inline elements (display: inline), which is usually not desired for components. So custom components usually have at least display: (inline-)block to change the default display mode of elements.

Self-closure of components

Self-closure includes two aspects: self-closure of data and self-closure of style.

Self-enclosure of data

angular 1 In angular 1, the component's own scope is already isolated (isolate), that is, the component's scope does not inherit from the parent scope ( __proto__ is null

). In addition, a canonical component should not directly use external data, because this will destroy the reusability of the component. Here are a few examples:
  1. $rootScope
  2. $root, $parent (in template)
  3. Routing parameters
  4. localStorage, sessionStorage

##These data should be passed in through parameter binding binding. If the component is generated by a routing plug-in, resolve can be used.

Secondly, parameter binding should not use two-way binding =, and standardized components should not (directly) modify data passed in outside the component. There are two officially recommended parameter binding methods

  1. 单向绑定,绑定可变数据。通常用于给组件传递数据

  2. @ 字符串绑定,绑定字符串。通常用于指定组件行为

对于单向绑定对象的情况,由于是引用传递,也不应该修改对象内部的属性。

遇到要向外部传值的情况,推荐使用 ngModel 或 事件绑定(下面会提到)

样式的自封闭性

组件间的样式不应该互相干扰,这一点可以简单的通过 scss 的样式嵌套(Nesting)实现:

custom-dialog {
    display: block;
    // ...

    .title {
        // ...
    }

    .body {
        // ...
    }
}

这样可以简单的把组件的内置样式表限制在组件内部,从而避免样式外溢。但是这种方法对在组件内部的其他组件不起效果。如果这个组件的模板中还引用了别的组件,或者这个组件被定义为可嵌入的(transclude),那么可以考虑加类名前缀:

custom-dialog {
    display: block;

    .custom-dialog {
        &-title {
            // ..
        }

        &-body {

        }
    }
}

组件的可复用性

组件为复用而生,拥有良好自封闭性的组件必然是可复用的,因为这个组件不受任何外部因素干扰。组件的复用形式包括

  1. 一个页面中使用多次

  2. 在多个页面中使用

  3. ng-repeat

  4. 自己套自己(递归树结构)

  5. 整个源代码拷贝到其他项目中

等等。一个高度可复用的组件则可以被称为控件,是可以单独投稿 npm 项目库的。

当然,有些组件(比如单独的页面)可能复用需求没那么高,可以视组件的复用程度不同,从组件的自封闭性和整体代码量做一些取舍。

组件的定制化

一个高度可复用的组件一定可以被定制。

行为的定制化

通过参数绑定实现组件行为的定制化。例如:

<custom-dialog><!-- 与标签名一样,自定义属性名也应该使用中划线 -->
    <!--content -->
</custom-dialog>
module.component('customDialog', {
    template: require('./customDialogTemplate.html'),
    transclude: true,
    bindings: {
        title: "@",
        modal: '<p>出于使用方便的考虑,定制用的参数都是可选的,组件内部实现应该给每个定制参数设定默认值。(想看更多就到PHP中文网<a href="http://www.php.cn/course/47.html" target="_blank">angularjs学习手册</a>中学习)</p><h4 id="样式的定制化">样式的定制化</h4><p>组件风格定制可以使用 class 判断。</p><pre class="brush:php;toolbar:false">custom-dialog {
    display: block;
    // ...

    .title {
        font-size: 16px;
        // ...
    }

    &.big {
        .title {
            font-size: 24px;
        }
    }
}

使用时

<custom-dialog></custom-dialog>

深度定制样式比较好的方式是 CSS 属性(CSS Variable,注意不是 SCSS 属性)。

custom-dialog {
    display: block;
    // ...
    .title {
        font-size: 16px;
        color: var(--dialog-title-color, #333);
        // ...
    }
    &.big {
        .title {
            font-size: 24px;
        }
    }
}

这时只需要文档中说明标题颜色使用 --dialog-title-color 这个 CSS 变量就好,外部使用不依赖于组件内部 DOM 实现。使用时

.mydialog {
    --dialog-title-color: red;
}

组件的生命周期

从创建至销毁,组件有自己的生命周期(lifecycle),而不像指令那样把 scope 作为生命周期。常用的回调函数如下:

  • $onInit():组件被初始化时调用。与 constructor 不同,angular 1 确保 $onInit 被调用时组件的所有参数绑定都被正确赋值。

  • $onChanges(changeObj):组件参数绑定值被改变时调用。用于监听绑定值的变化,初次绑定时也会调用这个函数。

  • $onDestroy():组件被销毁时调用。用于清理内部资源如 $interval 等。

这些函数也是绑定在 this 上的。如果 controller 使用 ES2015class 定义方式,可以这么写:

class CustomDialogController {
    constructor() {}

    onInit() {}

    onChanges({ prop1, prop2 }) {}

    onDestroy() {}
}

组件间的通信

组件间通信是一个让很多人头疼的问题,通常有这样 3 种情况

子 -> 父

这种情况有标准的实现方式:事件绑定。例如

class CustomDialogController {
    close($value) {
        this.hide = true;
        this.onClose({ $value });
    }
}

module.component('customDialog', {
    controller: CustomDialogController,
    template: require('./customDialogTemplate.html'),
    bindings: {
        onClose: '&',
    },
});

使用时:

<custom-dialog></custom-dialog>

这种方式也可以用于子组件向父组件传值。

父 -> 子

用于触发子组件的某个动作。除了改变某个在子组件内部监听变化的绑定参数值外,行之有效的方式就只有事件广播。

子组件先监听某个事件

$scope.$on('custom-dialog--close', () => this.close());

父组件发送广播

$scope.$broadcast('custom-dialog--close');

切记:事件是全局性的。当有组件复用的情况时请使用标识指定接收对象(BUS 模型);另外最好给事件名添加组件前缀。

同级组件

请通过父级组件中转

子 -> 某全局性组件

这个显示 Notification 时最常用。遇到这种情况时,可以封装服务(Service)。例如:

module.component('globalNotification', {
    controller: class GlobalNotificationController {
        constructor(notificationService) {
            notificationService.component = this;
        }

        show(props) {
            // ...
        }
    }
});

module.factory('notify', function NotifyService() {
    return {
        warn(msg) {
            this.show({ type: 'warn', text: msg });
        }
        error(msg) {
            this.show({ type: 'error', text: msg });
        }
    }
});

方案并不完美。如果有更好的建议欢迎提出。

结语

有人可能问既然三大前端框架都是组件化的,何必还要在 angular 1 上实现。殊不知 angular 1 的组件诞生的初衷就是为了减少向 angular 2 迁移的难度。机会总是留给有准备的人,哪天老板大发慈悲表示给你把代码重写的时间,你却看着项目里满屏的 $scope.abc = xxx 不知所措,这岂不是悲剧。。。

This article ends here (if you want to see more, go to the PHP Chinese website angularjs Learning Manual). If you have any questions, you can leave a message below

The above is the detailed content of In-depth analysis of Angularjs1 component programming (with examples included). For more information, please follow other related articles on the PHP Chinese website!

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
Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

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),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools