Last active
March 26, 2016 17:25
-
-
Save marcoszf/270597d46e5b6bf39b36 to your computer and use it in GitHub Desktop.
Angularjs Directives - CONCEITUAL Básico - Referência
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Ref: http://ng-learn.org/2014/01/Dom-Manipulations/ | |
| para escrever.. | |
| /** O que são Directives? Ref: https://docs.angularjs.org/guide/directive **/ | |
| 'Em alto nível são markers em elementos DOM (como atributos, elementos name, comments e css class) ' | |
| 'que diz ao Angularjs HTML compiler ($compiler) para atribuir um específico ' | |
| 'comportamento aquele elemento DOM ou mesmo transformar o elemento DOM e seus filhos. ' | |
| 'O angular vem com um conjunto de directives como: ngBind, ngModel e ngClass.' | |
| /** Matching(associando) Directives **/ | |
| 'Antes de podermos escrever uma directive, precisamos saber como o Angular determina quando usar uma dada directive.' | |
| <input ng-model="foo"> //O elemento <input> associa-se a directive ngModel | |
| <person>{{name}}</person> //associa a {{person}} directive | |
| /** Normalização **/ | |
| 'Angular normaliza elementos tag e name atribute para determinar qual elemento associa a qual directive' | |
| 'Tipicamente referimos a directive por seu case-sensitive camelCase normalizado (ex ngModel).' | |
| 'contudo, o HTML é case-insensitive, portanto no DOM as directives são referidas por lower-case forms' | |
| 'utilizando dash-delimited ex: ng-model'. | |
| /** Directive types **/ | |
| '$compile pode associar directives baseado em elementos names, attributes, class names e comments ex:' | |
| <my-dir></my-dir> | |
| <span my-dir="exp"></span> | |
| <!-- directive: my-dir exp --> | |
| <span class="my-dir: exp;"></span> | |
| /* Criando Directives */ | |
| 'Assim como controllers, directives são registradas por modulos. Para registrar uma directive. utilize API' module.directive | |
| 'Best Practice: não utilize nomes com prefixo "ng" ou algo como "carousel" para evitar futuros conflitos' | |
| 'uma boa prática é utilizar um prefixo próprio como "meu" ou "my" -> myCustomer' | |
| /* Template-expanding directive */ | |
| 'Vamos supor q vc tenha um pedaço de template de informações que se repetirão muitas vezes no seu código.' | |
| 'Quando vc muda em um lugar, é preciso mudar em muitos outros. está é uma boa oportunidade de utilizar directives' | |
| //Uma dictive q simplesmente substitui seu conteúdo por um template estático | |
| angular.module('docsSimpleDirective', []) | |
| .controller('Controller', ['$scope', function($scope) { | |
| $scope.customer = { | |
| name: 'Naomi', | |
| address: '1600 Amphitheatre' | |
| }; | |
| }]) | |
| .directive('myCustomer', function() { | |
| return { | |
| template: 'Name: {{customer.name}} Address: {{customer.address}}' | |
| }; | |
| }); | |
| <div ng-controller="Controller"> | |
| <div my-customer></div> | |
| </div> | |
| 'Best Practice: A menos que seu template seja muito pequeno, é melhor quebra-lo em seu próprio arquivo HTML e carrega-lo ' | |
| 'utilizando a opção ' templateUrl: //código abaixo: https://my.modulus.io/project-not-found?url=plnkr.co | |
| //scripts.js | |
| angular.module('docsTemplateUrlDirective', []) | |
| .controller('Controller', ['$scope', function($scope) { | |
| $scope.customer = { | |
| name: 'Naomi', | |
| address: '1600 Amphitheatre' | |
| }; | |
| }]) | |
| .directive('myCustomer', function() { | |
| return { | |
| templateUrl: 'my-customer.html' | |
| }; | |
| }); | |
| //index.html | |
| <div ng-controller="Controller"> | |
| <div my-customer></div> | |
| </div> | |
| //my-customer.html | |
| Name: {{customer.name}} Address: {{customer.address}} | |
| /* Restrições(restrict) */ | |
| 'Quando vc cria uma directive, ela é restrita para atributos e elementos por padrão. A fim de criar ' | |
| 'directives que são "triggered" por class name, vc precisa utilizar a opção: ' restrict | |
| 'A' - only matches attribute name; 'E' - only matches element name; | |
| 'C' - only matches class name; 'M' - only matches comment; | |
| 'AEC' - matches either attribute or element or class name; | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* Criando Directive que manipula DOM */ | |
| 'Directives que quer modificar a DOM utiliza a opção' link 'para registrar o DOM listeners bem como atualizar o DOM' | |
| link 'tem uma função com a seguinte assinatura: ' | |
| function link(scope, element, attrs, controller, transcludeFn) { ... } | |
| - scope: 'é um Angular scope object.' | |
| - element: 'é um jqLite-wrapped element que está directive associa' | |
| - attrs: 'is a hash object with key-value pairs of normalized attribute names and their corresponding attribute values' | |
| - controller: 'is the directive's 'required controller instance(s) or its own controller (if any). The exact value depends on the directive-s require property.' | |
| - transcludeFn: 'is a transclude linking function pre-bound to the correct transclusion scope' | |
| //Plunker - http://plnkr.co/edit/L0IYUWRM4LCdXcrKDJeW?p=preview | |
| angular.module('docsTimeDirective', []) | |
| .controller('Controller', ['$scope', function($scope) { | |
| $scope.format = 'M/d/yy h:mm:ss a'; | |
| }]) | |
| .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval, dateFilter) { | |
| function link(scope, element, attrs) { | |
| var format, | |
| timeoutId; | |
| function updateTime() { | |
| element.text(dateFilter(new Date(), format)); | |
| } | |
| scope.$watch(attrs.myCurrentTime, function(value) { | |
| format = value; | |
| updateTime(); | |
| }); | |
| element.on('$destroy', function() { | |
| $interval.cancel(timeoutId); | |
| }); | |
| // start the UI update process; save the timeoutId for canceling | |
| timeoutId = $interval(function() { | |
| updateTime(); // update DOM | |
| }, 1000); | |
| } | |
| return { | |
| link: link | |
| }; | |
| }]); | |
| <div ng-controller="Controller"> | |
| Date format: <input ng-model="format"> <hr/> | |
| Current time is: <span my-current-time="format"></span> | |
| </div> | |
| 'Just like' module.controller 'API, the function argument in module.directive is dependency injected.' | |
| 'Because of this, we can use $interval and dateFilter inside our directive-s link function.' | |
| 'Registramos um evento ' element.on('$destroy', ...). 'O que dispara este $destroy evento ?' | |
| 'Há alguns eventos especiais que AngularJs emite. Quando um DOM node que foi compilado pelo AngularJs compilador é destruído' | |
| 'ele emite um evento:' $destroy 'similar a quando um Angular scope é destruído, it broadcasts a $destroy event to listening scopes' | |
| 'By listening to this event, você pode remover eventos listeners que podem causar vazamento de memória' | |
| 'Listeners registered to scopes and elements are automatically cleaned up when they are destroyed, ' | |
| 'but if you registered a listener on a service, or registered a listener on a DOM node that isnt being deleted, ' | |
| 'you-ll have to clean it up yourself or you risk introducing a memory leak' | |
| Best Practice: Directives should clean up after themselves. You can use element.on('$destroy', ...) or scope.$on('$destroy', ...) to run a clean-up function when the directive is removed. | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* Creating a Directive that Adds Event Listeners */ | |
| //Plunker - http://plnkr.co/edit/h6Npqo5S1UnVfn4isFg7?p=preview | |
| angular.module('dragModule', []) | |
| .directive('myDraggable', ['$document', function($document) { | |
| return { | |
| link: function(scope, element, attr) { | |
| var startX = 0, startY = 0, x = 0, y = 0; | |
| element.css({ | |
| position: 'relative', | |
| border: '1px solid red', | |
| backgroundColor: 'lightgrey', | |
| cursor: 'pointer' | |
| }); | |
| element.on('mousedown', function(event) { | |
| // Prevent default dragging of selected content | |
| event.preventDefault(); | |
| startX = event.pageX - x; | |
| startY = event.pageY - y; | |
| $document.on('mousemove', mousemove); | |
| $document.on('mouseup', mouseup); | |
| }); | |
| function mousemove(event) { | |
| y = event.pageY - startY; | |
| x = event.pageX - startX; | |
| element.css({ | |
| top: y + 'px', | |
| left: x + 'px' | |
| }); | |
| } | |
| function mouseup() { | |
| $document.off('mousemove', mousemove); | |
| $document.off('mouseup', mouseup); | |
| } | |
| } | |
| }; | |
| }]); | |
| <span my-draggable>Drag Me</span> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment