+2

AngularJS Directive

AngularJS Directives

Đầu tiên mình xin giới thiệu khái niệm Directive trong AngularJs

Khái Niệm

Directives là 1 đối tượng mà chúng ta có thể định nghĩa nó thông qua các thuộc tính của các thẻ HTML. Hay theo Angular nó là các properties của các thẻ HTML.

Cách đặt tên 1 Directives:

ng-prefix (trong đó ng luôn luôn phải xuất hiện trong directives và prefix là tên mà directives mà chúng ta sử dụng)

VD: ng-controller, ng-model, ng-app, ng-bind

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Example Directive</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
    <script language="javascript">
      var myApp = angular.module("myApp", []);
      myApp.controller("calculator", function($scope){
	  $scope.calculate = function(){
		var numberA = parseInt($scope.numberA);
		var numberB = parseInt($scope.numberB);
		var calculation = $scope.calculations;
		if(calculation == "+"){
			$scope.result = "Result: " + (numberA + numberB);
		}
		if(calculation == "-"){
			$scope.result = "Result: " + (numberA - numberB);
		}
		if(calculation == "*"){
			$scope.result = "Result: " + (numberA * numberB);
		}
		if(calculation == "/"){
			$scope.result = "Result: " + (numberA / numberB);
		}
	   }
     });
    </script>
  </head>
  <body ng-app="myapp">
    <div ng-controller="calculator">
    Enter number A: <input ng-model="numberA">
    Enter number B: <input ng-model="numberB">
    <select ng-model="calculations">
      <option value="+">+</option>
      <option value="-">-</option>
      <option value="*">x</option>
      <option value="/">/</option>
    </select>
    <button ng-click="calculate()">Calculate</button>
    <span>{{result}}</span>
    </div>
  </body>
</html>

Trong ví dụ trên chúng ta có sử dụng đến các directive ng-controller, ng-app, ng-click, ng-model để có thể tính toán giữa 2 số nhập vào

Danh sách các Angular Directives

Trong giới hạn bài mình không thể kể hết được các Directives trong Angular, vì vậy mình xin tóm tắt 1 số Directive đơn giản và dễ hiểu thôi nhé Các bạn có thể lên https://docs.angularjs.org/api để tham khảo

  • ng-app : Khi chúng ta khai báo một Directive ng-app thì AngularJS sẽ hiểu là bắt đầu một ứng dụng Angular, nó sẽ xác định đây là thẻ gốc (element root) và tiếp theo sẽ khởi tạo các thông số cấu hình bên trong mà ta gọi là bootstraps. Ngoài ra ng-app còn được sử dụng để mô tả các module khác nhau trong ứng dụng.
  • ng-model: Khi liên kết dữ liệu với client
  • ng-init : Khai báo dữ liệu khởi tạo khi ứng dụng khởi chạy (các dữ liệu này sẽ được dùng cho toàn bộ phạm controller mà nó thuộc về)...

Tự tạo 1 Directives

Tức là ngoài các Directives mà Angular tạo ra. thì mình cũng có thể tự tạo 1 Directives cho riêng mình

Đầu tiền directive cũng phải registered với module. Đăng ký directive với cú pháp module.directive từ đây sẽ tạo ra một normalized directive và kèm theo một factory function. Factory này trả về một object với nhiều option khác nhau. Và factory fuction này được gọi mỗi khi compiler match với directive ở lần đầu tiên.

Note: Khi tạo directive bạn nên tạo ra một directive có tiền tố của riêng bạn để tránh việc xung đột với các thẻ html đặc biệt là không được tạo directive với tiền tố là ng.

Và bây giờ chúng ta sẽ đi sâu tìm hiểm 1 số cấu trúc trong custome directive

  • Directive template/templateUrl
  var myApp = angular.module("myApp", [])

  myApp.directive("directive", function(){
    return {
      template: "<b>Directive AngularJS</b>",
      templateUrl: //dường dẫn file HTML
    }
  });
  • Directive Restrict
  var myApp = angular.module("myApp", [])

  myApp.directive("directive", function(){
    return {
      restrict: "A"  (A : attributes, E: Element, C: class)
      template: "<b>Directive AngularJS</b>",
    }
  });

restrict chỉ định ta có thể sử dụng directive ở trong A/E/C của HTML (note: default Attributes)

  • Directive Talking To Controller là 1 directive gọi đến các hàm trong controller như thế nào?

  var myApp = angular.module("myApp", []);

  myApp.controller("myController", function($scope){
    $scope.showAlert = function(){
  	  alert("OK");
    };
  });

  myApp.directive("directive", function(){
	return function(scope, attrs, element){
	  scope.showAlert();
	};
  });

Directive sẽ goi đến function showAlert trong controller thông qua biến scope vì directive nằm trong controller nên biến $scope trong controller sẽ chính là biến scope trong directive

  • Directive Linking

như ở trên mình viết directive return về 1 function thì ở dưới này mình sẽ dùng link để return về 1 funtion trong directive


  var myApp = angular.module("myApp", []);

  myApp.controller("myController", function($scope){
    $scope.showAlert = function(){
  	  alert("OK");
    };
  });

  myApp.directive("directive", function(){
	return {
      link : function(scope){
	    scope.showAlert();
      }
	};
  });
  • Directive Isolating (@, = , &) Directive có thể mang scope riêng của mình nói rõ hơn về các ký tự @, =, &

@ Kết nối giá trị của property trong scope con với các attribute html của directive (đối với string)

= Liên kết property của scope con với property của scope cha bẳng two-way binding (đối với handler)

& Liên kết hàm Expression của Angular tới property của scope con. (đối với function)

VD mình sẽ code sửa dụng Directive Isolating (&) là đối với function

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Example Directive</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
    <script language="javascript">
      var myApp = angular.module("myApp", []);

      myApp.controller("myController", function($scope){
        $scope.showAlert = function(msg){
          alert(msg);
        };
      });

	  myApp.directive("directive", function(){
        return {
          scope : {
            show : "&"
          },

        template : "<input ng-model='message' /></br>" +
		  "<button ng-click='show({messages:message})'>Show</button>"
		};
	  });
    </script>
  </head>
  <body ng-app="myapp">
	<div ng-controller="myController">
	  <div directive show="showAlert(messages)">Directive AngularJS</div>
	</div>
  </body>
</html>
  • Priority Giúp quyết định thứ tự ưu tiên trong 1 element khi chứa nhiều directive note: giá trị càng cao thì độ ưu tiên càng cao - nếu giá trị bằng nhau thì độ ưu tiên không được đảm bảo

  • Transclude Có thể child element của directive

  var myApp = angular.module("myApp", [])

  myApp.directive("directive", function(){
    transclude: true,
    return {
      template: "<div ng-transclude>Directive AngularJS</div>",
    }
  });

Note: default : false

Tổng hợp lại Custome Directive :

myApp.directive('customDirective', function(){
  return{
    restrict: 'ACE',
    priority: 0,
    transclude: true,
    replace: false,
    template: '<span>{{title}}</span>'
    scope: {
      myDirective: '=',
      onChange: '&',
      title: '@'
    },
    link: function postLink(scope, element, attrs, ctrl){
    },
    controller: ['$scope', function($scope){
    }]
  };
});

Mình đã viết xong bài tìm hiểu về Directive, cách khai báo 1 directive và custome directive. Mọi người có thể tham khảo thêm ở https://docs.angularjs.org/api/ng#directive nhé !!


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí