Khi tạo 1 directive, đầu tiên ta phải suy nghĩ xem ta viết cái gì? Sau đó ta xem directive của ta hoạt động ra sao? Và cuối cùng là ta truyền vào cái gì để nó hoạt động?
Để mô tả luồng tư duy, mình thử viết 1 modal directive cơ bản nhất:
– Viết cái gì: Modal
– Hoạt động: Modal có tính năng click vào button thì hiện lên, click vào background thì tắt đi.
– Truyền vào: Biến bật/tắt và Content của modal.
Sau khi tư duy xong, ta có thể khái quát được mô hình như sau:
– name directive: modalWindow
– replace: true (dĩ nhiên)
– transclude: true (vì cần truyền content vào modal, sau này cứ khi nào directive cần truyền dynamic content vào thì transclude là true hết)
– biến bật/tắt: show (false là tắt, true là bật)
Code của ta như sau:
<!DOCTYPE html> <html> <head> <title>TO DO List</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script> <style> .modal-overlay { position:absolute; z-index:9999; top:0; left:0; width:100%; height:100%; background-color:#000; opacity: 0.8; } .modal-background { z-index:10000; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: #fff; } .modal-content { padding:10px; text-align: center; } .modal-close { position: absolute; top: 5px; right: 5px; padding: 5px; cursor: pointer; display: inline-block; } </style> <script> // Creating a simple Modal Directive app = angular.module('SimpleModal', []); app.directive('modalWindow', function() { return { restrict: 'E', scope: { show: '=' }, replace: true, // Replace with template transclude: true, // To use custom content link: function(scope, element, attrs) { scope.windowStyle = {}; if (attrs.width) { scope.windowStyle.width = attrs.width; } if (attrs.height) { scope.windowStyle.height = attrs.height; } scope.hideModal = function() { scope.show = false; }; }, template: "<div ng-show='show'><div class='modal-overlay' ng-click='hideModal()'></div><div class='modal-background' ng-style='windowStyle'><div class='modal-close' ng-click='hideModal()'>X</div><div class='modal-content' ng-transclude></div></div></div>" }; }); app.controller('ModalCtrl', ['$scope', function($scope) { $scope.modalShown = false; $scope.toggleModal = function() { $scope.modalShown = !$scope.modalShown; }; }]); </script> </head> <body ng-app='SimpleModal'> <div ng-controller='ModalCtrl'> <button ng-click='toggleModal()'>Open Modal</button> <modal-window show='modalShown' width='400px' height='60%'> <p>Hello Simple Modal Window<p> </modal-window> </div> </body> </html>
Demo: https://jsbin.com/kopebucepa/edit?html,output