Home  >  Article  >  Web Front-end  >  How to use AngularJS directives? Angularjs instruction usage details (with code examples)

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

寻∝梦
寻∝梦Original
2018-09-08 16:37:561140browse

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>
    
  

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

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>

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

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

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>

"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: "
",     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);
    }
  }
});

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