Home Web Front-end JS Tutorial How to use Angularjs custom directives

How to use Angularjs custom directives

Jun 02, 2018 pm 02:00 PM
angularjs javascript customize

This time I will show you how to use Angularjs custom instructions and what are the precautions for using Angularjs custom instructions. The following is a practical case, let's take a look.

1: Commonly used templates for custom instructions

The following is a rough description, not comprehensive. Some unmentioned details and important related knowledge will be explained later. :

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

angular.module('yelloxingApp', []).directive('uiDirective'function() {

  return {  

    restrict:String,//标明该指令可以在模板中用于元素E、属性A、类C和注释M或组合    

    priority:Number,//设置指令执行优先级,在某个DOM上优先级高的会先执行

        terminal:Boolean,    

    template:String or Template Function,//就是设置模板,和下面的templateUrl属性二个只可以设置一个,目的一样    

    templateUrl:String or Template Function,//除了字符串,这二个属性还可以设置函数    

    replace:Boolean,//指令模板是否替换原来的元素    

    scope:Boolean or Object,

    controller:String or function(scope, element, attrs) { ... },    

    require:String or Array,    

    //你需要知道link在每个实例都执行一遍,compile全程只会执行一遍

    link: function(scope, element, attrs,ctrl) { ... },    

    compile:function(element, attrs) {

      //常用的就是compile的此处写执行一次的代码,或者在link方法里面写和dom有关的操作

    }

  };

});

Copy after login

2: Some attribute descriptions

[scope]

You can set boolean or objects. Let’s talk about boolean first. This is relatively simple:

1. When set to true, it means inheriting the parent scope and is a child scope;

2. When set to false, the parent scope is used directly.

There is another object setting method, which is to set an isolated scope. When using the isolated scope, three methods are provided to interact with places outside the isolation. Here is an example to illustrate one by one:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

angular.module('yelloxingApp', []).directive("scopeExample", ['$rootScope'function($rootScope) {

  return {

    restrict: 'A',    

    scope: {

      _userDataName: "=userDataName",

      _onSend: "&onSend",

      _fromName: "@fromName"

    },    

    template: `

      <button ng-click="_useParentMethod()">

        点击按钮调用父级的方法

      </button>

       

      <input ng-model="_userDataName"/>

      <ul>

        <li>fromName={{newfromname}}</li>

        <li>这是从父级获取到的{{_userDataName}}</li>

      </ul>`,

       link: function($scope, element, attrs) {

      //使用@符号可将本地作用域的变量与DOM属性的值进行绑定,即这里通过@得到父类fromName的值

      $scope.newfromname = $scope._fromName;

      $scope._useParentMethod = function() {      

        //使用&符号可以在其中调用父类的方法

        $scope._onSend({ "email": { "email""yelloxing@gmail.com" } });

        console.log($scope._userDataName);        

      };

    }

  };

}]);

Copy after login

The above is how to write the command. Let’s take a look at what’s inside Controller:

1

2

3

4

5

$scope.name = "心叶";

$scope.user = "yelloxing";

$scope.sendMail = function(email){

  console.error(email);

}

Copy after login

Finally, don’t forget the usage in html:

Copy code The code is as follows:

[require]

Request another controller, and then pass it in as the fourth parameter of the link method. What we need to pay attention to is to find the controller method.

The method of finding a controller can be understood like this: use? Indicates that if the required controller is not found in the current command, null will be passed as the fourth parameter to the link function. If the ^ prefix is ​​added, the command will search for the controller specified by the require parameter in the upstream command chain. , they can also be combined, such as require: "?^ngModel". If there is no prefix, the instruction will search in the controller provided by itself. If no controller (or instruction with the specified name) is found, it will throw a mistake.

[terminal]

Attribute terminal: When true, instructions with a priority lower than the current instruction will not be executed, and only this instruction will be executed.

Three: Data formatting between view and model

Function similar to filter, sometimes we want the page to display data It looks like it has been translated to facilitate agreement, but for the database, a simple serial number may be more beneficial, so you may need to use the following method in the link to achieve this function:

1.ctrl. $formatters.unshift(function(input) {//Data formatting from model to view});

2.ctrl.$parsers.unshift(function(input) {//Data formatting from view to model change}).

The above $formatters and $parsers are two queues, view to model and model to view, which will facilitate filtering through the methods defined inside, somewhat similar to pipeline flow, and finally flow to the destination.

Don’t forget to set a statement like require: "?ngModel" to find the controller.

4: View and model data synchronization issues

Sometimes the input data is modified through jquery in the instruction, but angularjs will not know it. At this time, you You can choose one of the following methods:

1. Trigger the change of the input box, let Angularjs find that the data has changed, and then call $setViewValue(value) to synchronize the data: $("input").trigger( "change");

2. Directly manually trigger the behavior of synchronizing value to viewValue and modelValue: ctrl.$setViewValue($scope.info).

Five: Several fragmentary skills
1. Set true or false according to whether the input box is legal: ctrl.$setValidity(errorType, boolean);//errorType represents the error category and can be customized

2. Set up a specified model value for monitoring, and of course there are methods such as monitoring collections: $scope.$watch(attrs['ngModel'], function(newValue, oldValue) {});

3. Sometimes the newly added string in the instruction needs to be managed by angularjs, you can use the following method to compile it: $compile(newHtml)($scope).

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to use Angular CLI to create an Angular project

How to use JS to implement Huffman coding

The above is the detailed content of How to use Angularjs custom directives. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to quickly set up a custom avatar in Netflix How to quickly set up a custom avatar in Netflix Feb 19, 2024 pm 06:33 PM

An avatar on Netflix is ​​a visual representation of your streaming identity. Users can go beyond the default avatar to express their personality. Continue reading this article to learn how to set a custom profile picture in the Netflix app. How to quickly set a custom avatar in Netflix In Netflix, there is no built-in feature to set a profile picture. However, you can do this by installing the Netflix extension on your browser. First, install a custom profile picture for the Netflix extension on your browser. You can buy it in the Chrome store. After installing the extension, open Netflix on your browser and log into your account. Navigate to your profile in the upper right corner and click

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

How to customize shortcut key settings in Eclipse How to customize shortcut key settings in Eclipse Jan 28, 2024 am 10:01 AM

How to customize shortcut key settings in Eclipse? As a developer, mastering shortcut keys is one of the keys to improving efficiency when coding in Eclipse. As a powerful integrated development environment, Eclipse not only provides many default shortcut keys, but also allows users to customize them according to their own preferences. This article will introduce how to customize shortcut key settings in Eclipse and give specific code examples. Open Eclipse First, open Eclipse and enter

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

The operation process of edius custom screen layout The operation process of edius custom screen layout Mar 27, 2024 pm 06:50 PM

1. The picture below is the default screen layout of edius. The default EDIUS window layout is a horizontal layout. Therefore, in a single-monitor environment, many windows overlap and the preview window is in single-window mode. 2. You can enable [Dual Window Mode] through the [View] menu bar to make the preview window display the playback window and recording window at the same time. 3. You can restore the default screen layout through [View menu bar>Window Layout>General]. In addition, you can also customize the layout that suits you and save it as a commonly used screen layout: drag the window to a layout that suits you, then click [View > Window Layout > Save Current Layout > New], and in the pop-up [Save Current Layout] Layout] enter the layout name in the small window and click OK

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

See all articles