


This article mainly introduces the instruction examples about angularjs. The first one is to use the accordion instruction instance in angularjs, and also defines the instructions. Now let us take a look at this article. Bar
Preface about angularjs:
We have introduced all the basic knowledge of AngularJS before. Let us deepen our memory and experience customization through examples. The joy of instruction.
Accordion command
The first example we show is the accordion effect command:
The effect picture is as follows:
Online example Address: Accordion command
The pure HTML source code without AngularJS is as follows:
<p> </p><p> </p><p> <a> Collapsible Group Item #1 </a> </p> <p> </p><p> Anim pariatur cliche... </p> <p> </p><p> <a> Collapsible Group Item #2 </a> </p> <p> </p><p> Anim pariatur cliche... </p>
The above pure HTML source code can also achieve the accordion effect, but it is just some tags, including A large number of links and IDs are not conducive to maintenance.
Using AngularJS custom instructions combined with the following HTML source code can also get the expected effect:
<h3 id="BootStrap手风琴指令">BootStrap手风琴指令</h3> <btst-accordion> <btst-pane>基本功能" category="{name:'test'}"> <p>AngularJS......</p> </btst-pane> <btst-pane>创建自定义指令"> <p>使用过 AngularJS ......</p> </btst-pane> <btst-pane>体验实例"> <p>之前我们已经介绍了所有的AngularJS......</p> </btst-pane> </btst-accordion>
This version uses fewer HTML tags, Looks clear and easy to maintain.
Next, let’s take a look at how to write instructions.
First, we define the module "btstAccordion" directive:
var btst = angular.module("btst", []); btst.directive("btstAccordion", function () { return { restrict: "E", transclude: true, replace: true, scope: {}, template: "<p></p>", link: function (scope, element, attrs) { // 确保 accordion拥有id var id = element.attr("id"); if (!id) { id = "btst-acc" + scope.$id; element.attr("id", id); } // set data-parent and href attributes on accordion-toggle elements var arr = element.find(".accordion-toggle"); for (var i = 0; i <p></p><p>Since it has internal HTML content, set the transclude attribute of the directive to true. The template uses the ng-transclude directive to declare the corresponding display content. Since there is only one element in the template, no other options are set. </p><p>The most interesting part of the code is the link method. It takes effect when the parameter element has an id. If not, the ID will be automatically created based on the Scope of the instruction. Once the element has an ID value, the method will use jQuery to select the child element with the "accordion-toggle" class and set its "data-parent" and "href" attributes. Finally, by looking for the "accordion-body" element and setting the "collapse" attribute. The </p><p> directive also declares a controller with an empty method. Declaring the controller is necessary because the Accordion will contain child elements, which will detect the type and controller of the parent element. </p><h2 id="The-next-step-is-to-define-the-instructions-for-the-accordion-tab">The next step is to define the instructions for the accordion tab. </h2><p>This step is easy, most operations will happen in this template, but it only requires a small amount of code: </p><p class="cnblogs_code" style="background-color:#f5f5f5;border:#cccccc 1px solid;"></p><pre class="brush:php;toolbar:false">btst.directive('btstPane', function () { return { require: "^btstAccordion", restrict: "E", transclude: true, replace: true, scope: { title: "@" }, template: "<p>" + " </p><p>" + " <a>{{title}}</a>" + " </p>" + "<p>" + " </p><p></p>" + " " + "", link: function (scope, element, attrs) { scope.$watch("title", function () { // NOTE: this requires jQuery (jQLite won't do html) var hdr = element.find(".accordion-toggle"); hdr.html(scope.title); }); } }; });
require attribute The value is "btstPane", so this directive must be used in the directive "btstAccordion". The transclude attribute is true to indicate that the tab contains HTML tags. The "title" attribute under scope will be replaced by the instance.
The template in this example is more complex. Notice that we mark the element to receive text content via the ng-transclude directive.
The "{{title}}" attribute in the template will display the tag name. At present, we only implement plain text display and do not define its style. We use the link method to replace the title with HTML source code to get a richer style. (If you want to see more, go to the PHP Chinese websiteAngularJS Development Manual to learn)
In this way, we completed the first instruction with practical value. Its function is not complicated but it is enough to demonstrate some important knowledge points and technical details of AngularJS: how to define nested directives, how to generate unique element IDs, how to use jQuery to manipulate the DOM and how to use the $watch method to monitor changes in scope variables.
Google Maps Directive
The next example is a directive to create a Google Map:
Google Maps Directive
After we create the directive Previously, we needed to add a Google APIs reference to the page:
<!-- required to use Google maps --> <script> </script>
Next, we created the directive:
var app = angular.module("app", []); app.directive("appMap", function () { return { restrict: "E", replace: true, template: "<p></p>", scope: { center: "=", // Center point on the map markers: "=", // Array of map markers width: "@", // Map width in pixels. height: "@", // Map height in pixels. zoom: "@", // Zoom level (from 1 to 25). mapTypeId: "@" // roadmap, satellite, hybrid, or terrain },
The center property is bidirectionally bound. This application can change the map center and interact with the map (when the user selects the map location via the mouse button). At the same time, the map will also notify the application to update the current displayed location when the user scrolls to select the map location.
The markers property is defined as a reference because it is in array form, and serializing it into a string is time-consuming. The link method can implement the following functions:
1. Initialize the map
2. Update the map when the user view variable changes
3. Listen for the following events
Is the implementation code:
link: function (scope, element, attrs) { var toResize, toCenter; var map; var currentMarkers; // listen to changes in scope variables and update the control var arr = ["width", "height", "markers", "mapTypeId"]; for (var i = 0, cnt = arr.length; i <p></p><p>监测方法正如我们在文章开始时描述的,变量发生变化后,它将调用updateControl 方法。updateControl 方法实际上使用selected 选项创建了新的地图。</p><p>"zoom" 和 "center" 变量将被分别处理,因为我们不希望每次在用户选择或缩放地图时都重新创建地图。这两个方法检测地图是否重新创建还是仅仅是简单的更新。</p><p>以下是updateControl 方法的实现方法:</p><p class="cnblogs_code" style="background-color:#f5f5f5;border:#cccccc 1px solid;"></p><pre class="brush:php;toolbar:false">// update the controlfunction updateControl() { // get map options var options = { center: new google.maps.LatLng(40, -73), zoom: 6, mapTypeId: "roadmap" }; if (scope.center) options.center = getLocation(scope.center); if (scope.zoom) options.zoom = scope.zoom * 1; if (scope.mapTypeId) options.mapTypeId = scope.mapTypeId; // create the map and update the markers map = new google.maps.Map(element[0], options); updateMarkers(); // listen to changes in the center property and update the scope google.maps.event.addListener(map, 'center_changed', function () { if (toCenter) clearTimeout(toCenter); toCenter = setTimeout(function () { if (scope.center) { if (map.center.lat() != scope.center.lat || map.center.lng() != scope.center.lon) { scope.center = { lat: map.center.lat(), lon: map.center.lng() }; if (!scope.$$phase) scope.$apply("center"); } } }, 500); }
updateControl 方法首先需要接收Scope设置相关参数,接着使用options 创建和初始化地图。这是创建JavaScript指令的常见模式。
创建地图之后,方法会在更新标记的同时添加检测事件,以便监视地图中心位置的变化。该事件会监测当前的地图中心是否和Scope中的相同。如果不同,即会更新scope,调用$apply 方法通知AngularJS属性已经更改。这种绑定方式为双向绑定。
updateMarkers 方法十分的简单,几乎和AngularJS分离,所以我们在这里就不介绍了。
除了这个地图指令特有的功能,这个例子还展示了:
1. 两个过滤器转换坐标为常规数字到地理位置,例如33°38'24"N, 85°49'2"W。
2. 一个地理编码器,转换成地址的地理位置(也是基于谷歌的API)。
3. 使用HTML5的地理定位服务来获取用户当前位置的方法。
Wijmo Grid 指令
最后一个例子是可编辑的表格指令:
Wijmo Grid 指令
这里展示的图表插件是 Wijmo 前端插件套包中的一款插件 wijgrid 插件:
<wij-grid> <wij-grid-column> </wij-grid-column> <wij-grid-column> </wij-grid-column> <wij-grid-column> </wij-grid-column></wij-grid>
"wij-grid" 指令定制表格的属性,"wij-grid-column" 指令定制特性表格列的属性。以上标记定义了一个拥有三列的可编辑表格,分别为:“country”, "product" 和 "amount"。并且,以country列分组并且计算每个分组的合计。
这个指令中最特别的一点是 “wij-grid”和“wij-grid-column”的连接。为了使这个连接起作用,父指令中定义了如下controller:
app.directive("wijGrid", [ "$rootScope", "wijUtil", function ($rootScope, wijUtil) { return { restrict: "E", replace: true, transclude: true, template: "
关于controller 方法使用前文中提到的数组语法声明,在这个例子中,controller定义了addColumn 方法,它将会被"wij-grid-column" 指令调用。父指令会通过特定标记来访问列。
以下是"wij-grid-column" 指令的使用方法:
app.directive("wijGridColumn", function () { return { require: "^wijGrid", restrict: "E", replace: true, template: "<p></p>", scope: { binding: "@", // Property shown in this column. header: "@", // Column header content. format: "@", // Format used to display numeric values in this column. width: "@", // Column width in pixels. aggregate: "@", // Aggregate to display in group header rows. group: "@", // Whether items should be grouped by the values in this column. groupHeader: "@" // Text to display in the group header rows. }, link: function (scope, element, attrs, wijGrid) { wijGrid.addColumn(scope); } } });
require 成员用于指定"wij-grid-column" 指令的父级指令"wij-grid"。link 方法接收父指令的引用 (controller) ,同时通过addColumn 方法传递自身的scope 给父指令。scope 包含了表格用于创建列的所有信息。
更多指令
链接为一些AngularJS 指令的在线实例: http://wijmo.gcpowertools.com.cn/demo/AngularExplorer/ ,你可以在例子的基础上进行练习。例子都是严格的安照本文中的描述制作的,所以你可以无障碍学习他们。
本篇文章到这就结束了(想看更多就到PHP中文网AngularJS使用手册中学习),有问题的可以在下方留言提问。
The above is the detailed content of How to use AngularJS directives? Angularjs instruction usage details (with code examples). For more information, please follow other related articles on the PHP Chinese website!

Javascript 是一个非常有个性的语言. 无论是从代码的组织, 还是代码的编程范式, 还是面向对象理论都独具一格. 而很早就在争论的Javascript 是不是面向对象语言这个问题, 显然已有答案. 但是, 即使 Javascript 叱咤风云二十年, 如果想要看懂 jQuery, Angularjs, 甚至是 React 等流行框架, 观看《黑马云课堂JavaScript 高级框架设计视频教程》就对了。

在如今信息时代,网站已经成为人们获取信息和交流的重要工具。一个响应式的网站能够适应各种设备,为用户提供优质的体验,成为了现代网站开发的热点。本篇文章将介绍如何使用PHP和AngularJS搭建一个响应式网站,从而提供优质的用户体验。PHP介绍PHP是一种开源的服务器端编程语言,非常适用于Web开发。PHP具有很多优点,如易于学习、跨平台、丰富的工具库、开发效

随着互联网的不断发展,Web应用已成为企业信息化建设的重要组成部分,也是现代化工作的必要手段。为了使Web应用能够便于开发、维护和扩展,开发人员需要选择适合自己开发需求的技术框架和编程语言。PHP和AngularJS是两种非常流行的Web开发技术,它们分别是服务器端和客户端的解决方案,通过结合使用可以大大提高Web应用的开发效率和使用体验。PHP的优势PHP

随着互联网的普及,越来越多的人在使用网络进行文件传输和共享。然而,由于各种原因,使用传统的FTP等方式进行文件管理无法满足现代用户的需求。因此,建立一个易用、高效、安全的在线文件管理平台已成为了一种趋势。本文介绍的在线文件管理平台,基于PHP和AngularJS,能够方便地进行文件上传、下载、编辑、删除等操作,并且提供了一系列强大的功能,例如文件共享、搜索、

随着Web应用程序的普及,前端框架AngularJS变得越来越受欢迎。AngularJS是一个由Google开发的JavaScript框架,它可以帮助你构建具有动态Web应用程序功能的Web应用程序。另一方面,对于后端编程,PHP是非常受欢迎的编程语言。如果您正在使用PHP进行服务器端编程,那么结合AngularJS使用PHP将可以为您的网站带来更多的动态效

随着Web技术的飞速发展,单页Web应用程序(SinglePageApplication,SPA)已经成为一种越来越流行的Web应用程序模型。相比于传统的多页Web应用程序,SPA的最大优势在于用户感受更加流畅,同时服务器端的计算压力也大幅减少。在本文中,我们将介绍如何使用Flask和AngularJS构建一个简单的SPA。Flask是一款轻量级的Py

随着互联网的普及和发展,前端开发已变得越来越重要。作为前端开发人员,我们需要了解并掌握各种开发工具和技术。其中,PHP和AngularJS是两种非常有用和流行的工具。在本文中,我们将介绍如何使用这两种工具进行前端开发。一、PHP介绍PHP是一种流行的开源服务器端脚本语言,它适用于Web开发,可以在Web服务器和各种操作系统上运行。PHP的优点是简单、快速、便


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

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.

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