Table of Contents
Accordion command
BootStrap手风琴指令
First, we define the module "btstAccordion" directive:
The next step is to define the instructions for the accordion tab.
Google Maps Directive
Wijmo Grid 指令
Home Web Front-end JS Tutorial How to use AngularJS directives? Angularjs instruction usage details (with code examples)

How to use AngularJS directives? Angularjs instruction usage details (with code examples)

Sep 08, 2018 pm 04:37 PM
angularjs

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:

How to use AngularJS directives? Angularjs instruction usage details (with code examples)
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>
    
  
Copy after login

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>
Copy after login

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);
      });
    }
  };
});
Copy after login

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:

How to use AngularJS directives? Angularjs instruction usage details (with code examples)
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>
Copy after login

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
    },
Copy after login

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);
}
Copy after login

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 指令

最后一个例子是可编辑的表格指令:

How to use AngularJS directives? Angularjs instruction usage details (with code examples)

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>
Copy after login

"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: "
Copy after login
",     scope: {       data: "=",          // List of items to bind to.       allowEditing: "@",  // Whether user can edit the grid.       afterCellEdit: "&", // Event that fires after cell edits.       allowWrapping: "@", // Whether text should wrap within cells.       frozenColumns: "@"  // Number of non-scrollable columns    },     controller: ["$scope", function ($scope) {       $scope.columns = [];      this.addColumn = function (column) {         $scope.columns.push(column);       }     }],     link: function (scope, element, attrs) {      // omitted for brevity, see full source here:        // http://jsfiddle.net/Wijmo/jmp47/    }   } }]);

关于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);
    }
  }
});
Copy after login

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!

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)

The latest 5 angularjs tutorials in 2022, from entry to mastery The latest 5 angularjs tutorials in 2022, from entry to mastery Jun 15, 2017 pm 05:50 PM

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

Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Jun 27, 2023 pm 07:37 PM

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

Build web applications using PHP and AngularJS Build web applications using PHP and AngularJS May 27, 2023 pm 08:10 PM

With the continuous development of the Internet, Web applications have become an important part of enterprise information construction and a necessary means of modernization work. In order to make web applications easy to develop, maintain and expand, developers need to choose a technical framework and programming language that suits their development needs. PHP and AngularJS are two very popular web development technologies. They are server-side and client-side solutions respectively. Their combined use can greatly improve the development efficiency and user experience of web applications. Advantages of PHPPHP

How to use PHP and AngularJS for front-end development How to use PHP and AngularJS for front-end development May 11, 2023 pm 05:18 PM

With the popularity and development of the Internet, front-end development has become more and more important. As front-end developers, we need to understand and master various development tools and technologies. Among them, PHP and AngularJS are two very useful and popular tools. In this article, we will explain how to use these two tools for front-end development. 1. Introduction to PHP PHP is a popular open source server-side scripting language. It is suitable for web development and can run on web servers and various operating systems. The advantages of PHP are simplicity, speed and convenience

Use PHP and AngularJS to develop an online file management platform to facilitate file management Use PHP and AngularJS to develop an online file management platform to facilitate file management Jun 27, 2023 pm 01:34 PM

With the popularity of the Internet, more and more people are using the network to transfer and share files. However, due to various reasons, using traditional methods such as FTP for file management cannot meet the needs of modern users. Therefore, establishing an easy-to-use, efficient, and secure online file management platform has become a trend. The online file management platform introduced in this article is based on PHP and AngularJS. It can easily perform file upload, download, edit, delete and other operations, and provides a series of powerful functions, such as file sharing, search,

How to use AngularJS in PHP programming? How to use AngularJS in PHP programming? Jun 12, 2023 am 09:40 AM

With the popularity of web applications, the front-end framework AngularJS has become increasingly popular. AngularJS is a JavaScript framework developed by Google that helps you build web applications with dynamic web application capabilities. On the other hand, for backend programming, PHP is a very popular programming language. If you are using PHP for server-side programming, then using PHP with AngularJS will bring more dynamic effects to your website.

Build a single-page web application using Flask and AngularJS Build a single-page web application using Flask and AngularJS Jun 17, 2023 am 08:49 AM

With the rapid development of Web technology, Single Page Web Application (SinglePage Application, SPA) has become an increasingly popular Web application model. Compared with traditional multi-page web applications, the biggest advantage of SPA is that the user experience is smoother, and the computing pressure on the server is also greatly reduced. In this article, we will introduce how to build a simple SPA using Flask and AngularJS. Flask is a lightweight Py

Introduction to the basics of AngularJS Introduction to the basics of AngularJS Apr 21, 2018 am 10:37 AM

The content of this article is about the basic introduction to AngularJS. It has certain reference value. Now I share it with you. Friends in need can refer to it.

See all articles