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. :
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 inside Controller:
$scope.name = "心叶"; $scope.user = "yelloxing"; $scope.sendMail = function(email){ console.error(email); }
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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

Notepad++7.3.1
Easy-to-use and free code editor

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.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use
