Understanding AngularJs directives_AngularJS
命令については、特定の DOM 要素で実行される関数として単純に理解でき、命令はこの要素の機能を拡張できます。
まず完全なパラメーターの例を見て、次に各パラメーターの機能と使用法を詳しく紹介します。
angular.module('myApp', []) .directive('myDirective', function() { return { restrict: String, priority: Number, terminal: Boolean, template: String or Template Function: function(tElement, tAttrs) {...}, templateUrl: String, replace: Boolean or String, scope: Boolean or Object, transclude: Boolean, controller: String or function(scope, element, attrs, transclude, otherInjectables) { ... }, controllerAs: String, require: String, link: function(scope, iElement, iAttrs) { ... }, compile: // 返回一个对象或连接函数,如下所示: function(tElement, tAttrs, transclude) { return { pre: function(scope, iElement, iAttrs, controller) { ... }, post: function(scope, iElement, iAttrs, controller) { ... } } return function postLink(...) { ... } } }; });
1. 制限[文字列]
restrict はオプションのパラメータです。 DOM 内でディレクティブを宣言する方法を指定するために使用されます。デフォルト値は A で、属性として宣言されます。
オプションの値は次のとおりです:
E (要素)
<私のディレクティブ>私のディレクティブ>
A (プロパティ、デフォルト値)
C (クラス名)
M (コメント)
一般に、ブラウザの互換性を考慮して、デフォルトの属性を使用し、属性の形式で宣言することを強くお勧めします。最後の方法は、力インデックスが必要ない場合には使用しないことをお勧めします。
angular.module('app',[]) .directive('myDirective', function () { return { restrict: 'E', template: '<a href="http://www.baidu.com">百度</a>' }; }) HtmlCode: <my-directive></my-directive>
2. 優先度[int]
ほとんどのコマンドはこのパラメーターを無視し、デフォルト値 0 を使用しますが、高い優先順位を設定することが非常に重要である、または必要であるシナリオもあります。たとえば、ngRepeat はこのパラメータを 1000 に設定します。これにより、このパラメータは常に同じ要素上の他の命令より前に呼び出されます。
3. ターミナル[ブール]
このパラメータは、現在の要素でこの命令よりも優先度の低い命令の実行を停止するために使用されます。ただし、現在の命令と同じ優先順位を持つ命令は引き続き実行されます。
例: ngIf は ngView よりもわずかに高い優先順位を持ちます (実際に端末パラメータを制御します)。ngIf の式の値が true の場合、ngView は通常どおり実行できますが、ngIf 式の値が false の場合は、優先順位の関係で実行されます。 ngView のレベルが低い場合は実行されません。
4. テンプレート[文字列または関数]
テンプレート パラメータはオプションであり、次の 2 つの形式のいずれかに設定する必要があります:
- HTML テキストの一部;
- 2 つのパラメーター tElement と tAttrs を受け取り、テンプレートを表す文字列を返す関数。 tElement と tAttrs の t はテンプレートを表し、インスタンスに相対します。
-
angular.module('app',[]) .directive('myDirective', function () { return { restrict: 'EAC', template: function (elem, attr) { return "<a href='" + attr.value + "'>" + attr.text + "</a>"; } }; })
<my-directive value="http://www.baidu.com" text="百度"></my-directive> <div my-directive value="http://www.baidu.com" text="百度"></div>
5. templateUrl[文字列または関数]
templateUrl はオプションのパラメータであり、次のタイプを使用できます:
- 外部 HTML ファイルへのパスを表す文字列
- 2 つのパラメーター tElement と tAttrs を受け取り、外部 HTML ファイルへのパスを含む文字列を返す関数。
-
コード:
angular.module('app',[]) .directive('myDirective', function () { return { restrict: 'AEC', templateUrl: function (elem, attr) { return attr.value + ".html"; //当然这里我们可以直接指定路径,同时在模板中可以包含表达式 } }; })
6. replace[bool]
replace はオプションのパラメーターです。このパラメーターが設定されている場合、デフォルト値は false であるため、値は true である必要があります。デフォルト値は、テンプレートがこのディレクティブ を呼び出す要素内の子要素として挿入されることを意味します。
たとえば、上記の例では、デフォルト値を使用すると、生成される HTML コードは次のようになります:
<my-directive value="http://www.baidu.com" text="百度"><a href="http://www.baidu.com">百度</a></my-directive>
<a href="http://www.baidu.com" value="http://www.baidu.com" text="百度">百度</a>
据我观察,这种效果只有设置restrict="E"的情况下,才会表现出实际效果。
介绍完基本的指令参数后,就要涉及到更重要的作用域参数了...
7、scope参数[bool or object]
scope参数是可选的,可以被设置为true或一个对象。默认值是false。
如果一个元素上有多个指令使用了隔离作用域,其中只有一个可以生效。只有指令模板中的根元素可以获得一个新的作用域。因此,对于这些对象来说scope默认被设置为true。内置指令ng-controller的作用,就是从父级作用域继承并创建一个新的子作用域。它会创建一个新的从父作用域继承而来的子作用域。这里的继承就不在赘述,和面向对象中的继承基本是一直的。
首先我们来分析一段代码:
<div ng-app="app" ng-init="name= '祖父'"> <div ng-init="name='父亲'"> 第一代:{{ name }} <div ng-init="name= '儿子'" ng-controller="SomeController"> 第二代: {{ name }} <div ng-init="name='孙子'"> 第三代: {{ name }} </div> </div> </div> </div>
我们发现第一代,我们初始化name为父亲,但是第二代和第三代其实是一个作用域,那么他们的name其实是一个对象,因此出现的效果如下:
第一代:父亲
第二代: 孙子
第三代: 孙子
我们在修改一下代码,把第三代隔离开来再看看效果:
<div ng-app="app"ng-init="name= '祖父'"> <div ng-init="name='父亲'"> 第一代:{{ name }} <div ng-init="name= '儿子'" ng-controller="SomeController"> 第二代: {{ name }} <div ng-init="name='孙子'" ng-controller="SecondController"> 第三代: {{ name }} </div> </div> </div> </div>
JsCode:
angular.module('app', []) .controller('SomeController',function($scope) { }) .controller('SecondController', function ($scope) { })
效果如下:
第一代:父亲
第二代: 儿子
第三代: 孙子
在修改下代码来看看继承:
<div ng-app="app"ng-init="name= '祖父的吻'"> <div> 第一代:{{ name }} <div ng-controller="SomeController"> 第二代: {{ name }} <div ng-controller="SecondController"> 第三代: {{ name }} </div> </div> </div> </div>
效果如下:
第一代:祖父的吻
第二代: 祖父的吻
第三代: 祖父的吻
如果要创建一个能够从外部原型继承作用域的指令,将scope属性设置为true,简单来说就是可继承的隔离,即不能反向影响父作用域。
再来看个例子:
angular.module('myApp', []) .controller('MainController', function ($scope) { }) .directive('myDirective', function () { return { restrict: 'A', scope:false,//切换为{},true测试 priority: 100, template: '<div>内部:{{ myProperty }}<input ng-model="myProperty"/></div>' }; });
Html代码:
<div ng-controller='MainController' ng-init="myProperty='Hello World!'"> 外部: {{ myProperty}} <input ng-model="myProperty" /> <div my-directive></div> </div>
当我们改变scope的值我们会发现
false:继承但不隔离
true:继承并隔离
{}:隔离且不继承
8、transclude
transclude是一个可选的参数。默认值是false。嵌入通常用来创建可复用的组件,典型的例子是模态对话框或导航栏。我们可以将整个模板,包括其中的指令通过嵌入全部传入一个指令中。指令的内部可以访问外部指令的作用域,并且模板也可以访问外部的作用域对象。为了将作用域传递进去,scope参数的值必须通过{}或true设置成隔离作用域。如果没有设置scope参数,那么指令内部的作用域将被设置为传入模板的作用域。
只有当你希望创建一个可以包含任意内容的指令时,才使用transclude: true。
我们来看两个例子-导航栏:
<div side-box title="TagCloud"> <div class="tagcloud"> <a href="">Graphics</a> <a href="">ng</a> <a href="">D3</a> <a href="">Front-end</a> <a href="">Startup</a> </div> </div>
JsCode:
angular.module('myApp', []) .directive('sideBox', function() { return { restrict: 'EA', scope: { title: '@' }, transclude: true, template: '<div class="sidebox"><div class="content"><h2 class="header">' + '{{ title }}</h2><span class="content" ng-transclude></span></div></div>' }; });
这段代码告诉ng编译器,将它从DOM元素中获取的内容放到它发现ng-transclude指令的地方。
再来你看个官网的例子:
angular.module('docsIsoFnBindExample', []) .controller('Controller', ['$scope', '$timeout', function($scope, $timeout) { $scope.name = 'Tobias'; $scope.hideDialog = function () { $scope.dialogIsHidden = true; $timeout(function () { $scope.dialogIsHidden = false; }, 2000); }; }]) .directive('myDialog', function() { return { restrict: 'E', transclude: true, scope: { 'close': '&onClose' }, templateUrl: 'my-dialog-close.html' }; });
my-dialog-close.html
<div class="alert"> <a href class="close" ng-click="close()">×</a> <div ng-transclude></div> </div>
index.html
<div ng-controller="Controller"> <my-dialog ng-hide="dialogIsHidden" on-close="hideDialog()"> Check out the contents, {{name}}! </my-dialog> </div>
如果指令使用了transclude参数,那么在控制器无法正常监听数据模型的变化了。建议在链接函数里使用$watch服务。
9、controller[string or function]
controller参数可以是一个字符串或一个函数。当设置为字符串时,会以字符串的值为名字,来查找注册在应用中的控制器的构造函数.
angular.module('myApp', []) .directive('myDirective', function() { restrict: 'A', controller: 'SomeController' })
可以在指令内部通过匿名构造函数的方式来定义一个内联的控制器
angular.module('myApp',[]) .directive('myDirective', function() { restrict: 'A', controller: function($scope, $element, $attrs, $transclude) { // 控制器逻辑放在这里 } });
我们可以将任意可以被注入的ng服务注入到控制器中,便可以在指令中使用它了。控制器中也有一些特殊的服务可以被注入到指令当中。这些服务有:
1. $scope
与指令元素相关联的当前作用域。
2. $element
当前指令对应的元素。
3. $attrs
由当前元素的属性组成的对象。
<div id="aDiv"class="box"></div> 具有如下的属性对象: { id: "aDiv", class: "box" }
4. $transclude
嵌入链接函数会与对应的嵌入作用域进行预绑定。transclude链接函数是实际被执行用来克隆元素和操作DOM的函数。
angular.module('myApp',[]) .directive('myLink', function () { return { restrict: 'EA', transclude: true, controller: function ($scope, $element,$attrs,$transclude) { $transclude(function (clone) { var a = angular.element('<a>'); a.attr('href', $attrs.value); a.text(clone.text()); $element.append(a); }); } }; });
html
<my-link value="http://www.baidu.com">百度</my-link> <div my-link value="http://www.google.com">谷歌</div>
仅在compile参数中使用transcludeFn是推荐的做法。link函数可以将指令互相隔离开来,而controller则定义可复用的行为。如果我们希望将当前指令的API暴露给其他指令使用,可以使用controller参数,否则可以使用link来构造当前指令元素的功能性(即内部功能)。如果我们使用了scope.$watch()或者想要与DOM元素做实时的交互,使用链接会是更好的选择。使用了嵌入,控制器中的作用域所反映的作用域可能与我们所期望的不一样,这种情况下,$scope对象无法保证可以被正常更新。当想要同当前屏幕上的作用域交互时,可以使用传入到link函数中的scope参数。
10、controllerAs[string]
controllerAs参数用来设置控制器的别名,这样就可以在视图中引用控制器甚至无需注入$scope。
<div ng-controller="MainController as main"> <input type="text" ng-model="main.name" /> <span>{{ main.name }}</span> </div>
JsCode:
angular.module('myApp',[]) .controller('MainController', function () { this.name = "Halower"; });
控制器的别名使路由和指令具有创建匿名控制器的强大能力。这种能力可以将动态的对象创建成为控制器,并且这个对象是隔离的、易于测试。
11、 require[string or string[]]
require为字符串代表另外一个指令的名字。require会将控制器注入到其所指定的指令中,并作为当前指令的链接函数的第四个参数。字符串或数组元素的值是会在当前指令的作用域中使用的指令名称。在任何情况下,ng编译器在查找子控制器时都会参考当前指令的模板。
如果不使用^前缀,指令只会在自身的元素上查找控制器。指令定义只会查找定义在指令作当前用域中的ng-model=""
如果使用?前缀,在当前指令中没有找到所需要的控制器,会将null作为传给link函数的第四个参数。
如果添加了^前缀,指令会在上游的指令链中查找require参数所指定的控制器。
如果添加了?^ 将前面两个选项的行为组合起来,我们可选择地加载需要的指令并在父指令链中进行查找
如果没有任何前缀,指令将会在自身所提供的控制器中进行查找,如果没有找到任何控制器(或具有指定名字的指令)就抛出一个错误
12、compile【object or function】
compile选项本身并不会被频繁使用,但是link函数则会被经常使用。本质上,当我们设置了link选项,实际上是创建了一个postLink() 链接函数,以便compile() 函数可以定义链接函数。通常情况下,如果设置了compile函数,说明我们希望在指令和实时数据被放到DOM中之前进行DOM操作,在这个函数中进行诸如添加和删除节点等DOM操作是安全的。
compile和link选项是互斥的。如果同时设置了这两个选项,那么会把compile所返回的函数当作链接函数,而link选项本身则会被忽略。
编译函数负责对模板DOM进行转换。链接函数负责将作用域和DOM进行链接。 在作用域同DOM链接之前可以手动操作DOM。在实践中,编写自定义指令时这种操作是非常罕见的,但有几个内置指令提供了这样的功能。
13、link
compile: function(tEle, tAttrs, transcludeFn) { //todo: return function(scope, ele, attrs) { // 链接函数 };
链接函数是可选的。如果定义了编译函数,它会返回链接函数,因此当两个函数都定义时,编译函数会重载链接函数。如果我们的指令很简单,并且不需要额外的设置,可以从工厂函数(回调函数)返回一个函数来代替对象。如果这样做了,这个函数就是链接函数。
14、ngModel
它提供更底层的API来处理控制器内的数据,这个API用来处理数据绑定、验证、 CSS更新等不实际操作DOM的事情,ngModel 控制器会随 ngModel 被一直注入到指令中,其中包含了一些方法。为了访问ngModelController必须使用require设置.
ngModelController常用的元素如下:
1).为了设置作用域中的视图值,需要调用 ngModel.$setViewValue() 函数。
$setViewValue() 方法适合于在自定义指令中监听自定义事件(比如使用具有回调函数的jQuery插件),我们会希望在回调时设置$viewValue并执行digest循环。
angular.module('myApp') .directive('myDirective', function() { return { require: '?ngModel', link: function(scope, ele, attrs, ngModel) { if (!ngModel) return; $(function() { ele.datepicker({ //回调函数 onSelect: function(date) { // 设置视图和调用 apply scope.$apply(function() { ngModel.$setViewValue(date); }); } }); }); } }; });
2).$render方法可以定义视图具体的渲染方式
3).属性(这里属性可以参考前一篇文章末尾进行学习)
以上就是关于AngularJs指令的全部内容,希望对大家的学习有所帮助。

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to get items using commands in Terraria? 1. What is the command to give items in Terraria? In the Terraria game, giving command to items is a very practical function. Through this command, players can directly obtain the items they need without having to fight monsters or teleport to a certain location. This can greatly save time, improve the efficiency of the game, and allow players to focus more on exploring and building the world. Overall, this feature makes the gaming experience smoother and more enjoyable. 2. How to use Terraria to give item commands 1. Open the game and enter the game interface. 2. Press the "Enter" key on the keyboard to open the chat window. 3. Enter the command format in the chat window: "/give[player name][item ID][item quantity]".

This article aims to help beginners quickly get started with Vue.js3 and achieve a simple tab switching effect. Vue.js is a popular JavaScript framework that can be used to build reusable components, easily manage the state of your application, and handle user interface interactions. Vue.js3 is the latest version of the framework. Compared with previous versions, it has undergone major changes, but the basic principles have not changed. In this article, we will use Vue.js instructions to implement the tab switching effect, with the purpose of making readers familiar with Vue.js

Javascript is a very unique language. It is unique in terms of the organization of the code, the programming paradigm of the code, and the object-oriented theory. The issue of whether Javascript is an object-oriented language that has been debated for a long time has obviously been There is an answer. However, even though Javascript has been dominant for twenty years, if you want to understand popular frameworks such as jQuery, Angularjs, and even React, just watch the "Black Horse Cloud Classroom JavaScript Advanced Framework Design Video Tutorial".

Mobile devices have become an essential part of people's lives in modern society. Games have also become one of the main forms of entertainment in people's spare time. There are constantly people working on developing new tools and technologies to optimize gameplay and improve the gaming experience. The input method with its own MC command is one of the eye-catching innovations. And how it can bring a better gaming experience to players. This article will delve into the infinite possibilities of the built-in MC command input method. Introduction to the built-in MC command input method. The built-in MC command input method is an innovative tool that combines the functions of MC commands and intelligent input methods. This enables more operations and functions. By installing the input method on a mobile device, players can easily use various commands in the game. Enter commands quickly to improve game efficiency

In today's information age, websites have become an important tool for people to obtain information and communicate. A responsive website can adapt to various devices and provide users with a high-quality experience, which has become a hot spot in modern website development. This article will introduce how to use PHP and AngularJS to build a responsive website to provide a high-quality user experience. Introduction to PHP PHP is an open source server-side programming language ideal for web development. PHP has many advantages, such as easy to learn, cross-platform, rich tool library, development efficiency

The instructions that the computer can directly execute include operation codes and operands. The opcode refers to the part of the instruction or field specified in the computer program to perform the operation. It is actually the instruction sequence number, which is used to tell the CPU which instruction needs to be executed.

Instructions are commands that control computer execution, and they consist of operation codes and address codes. Usually an instruction includes two aspects: operation code and operand (address code). The operation code determines the operation to be completed, and the operand refers to the data participating in the operation and the address of the unit where it is located.

Xi Xiaoyao Technology said that the original author | IQ has dropped to the ground. Recently, many teams have re-created based on the user-friendly ChatGPT, and many of them have relatively eye-catching results. The InternChat work emphasizes user-friendliness by interacting with the chatbot in ways beyond language (cursors and gestures) for multimodal tasks. The name of InternChat is also interesting, representing interaction, nonverbal and chatbots, and can be referred to as iChat. Unlike existing interactive systems that rely on pure language, iChat significantly improves the efficiency of communication between users and chatbots by adding pointing instructions. In addition, the author also
