How to use Angularjs custom instructions in projects
This time I will show you how to use Angularjs custom instructions in projects, and what are the precautions for using Angularjs custom instructions in projects. 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. :
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有关的操作 } }; });
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:
angular.module('yelloxingApp', []).directive("scopeExample", ['$rootScope', function($rootScope) { return { restrict: 'A', scope: { _userDataName: "=userDataName", _onSend: "&onSend", _fromName: "@fromName" }, template: ` <button> 点击按钮调用父级的方法 </button> <input>
- fromName={{newfromname}}
- 这是从父级获取到的{{_userDataName}}
The above is how to write the command. Let’s take a look at what’s in the controller:
$scope.name = "心叶"; $scope.user = "yelloxing"; $scope.sendMail = function(email){ console.error(email); }
Finally, don’t forget to use it 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 the method of finding the controller.
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.
3: Data formatting between view and model
Similar to filter function, sometimes we want the page to display the data after some kind of translation to facilitate the 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) {//model到view的数据格式化}); 2.ctrl.$parsers.unshift(function(input) {//view到model的数据格式化})。
The above $formatters and $parsers are two A queue, view to model and model to view, will facilitate filtering through the methods defined in it, which is somewhat similar to a pipeline flow, and finally flows 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 discover 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: A few fragmentary techniques
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 a model value specified by the monitoring, and of course there are methods such as monitoring collections:
$scope.$watch(attrs['ngModel'], function(newValue, oldValue) {});
3. Sometimes in the command The newly added string needs to be managed by angularjs, so 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:
Detailed explanation of vue computed properties and listener practical projects
How to perform classes in JS TypeScript use
The above is the detailed content of How to use Angularjs custom instructions in projects. For more information, please follow other related articles on the PHP Chinese website!

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

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.

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 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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6
Visual web development tools

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools
