terça-feira, 15 de julho de 2014

A basic directive - Text Emphasis


  Nothing better than a real-world example to show why directives are so important.
  As you may already read somewhere (or everywhere), directives teach new tricks to HTML. 
  Let's start. Imagine you need to put some emphasis in certain words in your site. In angular, you can create a directive for that and use it wherever you want.


Let's go with the basic module and controller configuration
var app = angular.module('myApp',[]);

app.controller('myCtrl',function($scope){
});

Then let's create the directive
// you start by defining the name and callback function

app.directive('myDir',function(){
return{
restrict: 'E', // it'll be an element,
// and in html will be called by <my-dir>
// other options: 'A'ttribute, 'C'lass, co'M'ment
scope: {}, // isolated scope (will do a post about this)
link:
// this function will manipulate the DOM, if you wan't to
// play with jQuery you must use it here.
function(scope,element,attrs){
element.on('mouseenter',function(){
// when the mouse enters the word, a border will be applied to it
// and the size augmented.
$(this).css({'border':'1px solid #000;','font-size':'150%});
});
// now we need to remove the styles when the mouse leaves the word
element.on('mouseleave',function(){
$(this).css({'border':'none','font-size':'100%});
});
}
});
To apply it you need call the directive in your html like this:
  hello <my-dir>World</my-dir>
This is a simple example of how powerfull, yet simple, directives are. In very few lines of code, I did a component that I can use throughout my application, keeping the html clean and easier to read. You can check Demo Here.

Sem comentários:

Enviar um comentário