lets build a real simple custom directive with angular js, so directive implementation converts a couple of para into text slide show.
let see what i have done here,
in the html section
couple of tags a div which holds couple of paras which will be used to create a text slide show.
on the html tag there is a "ng-app" directive which bootstrap the angularjs. on div i have added my custom directive "text-slider". (is restricted 'A' to attribute)
in javascript section
starting off with angularjs module declaration since angularjs object is needed to define custom directive. a custom directive name as "textSlider", directive method take two arguments
directive name and function expression, injecting $interval service, to use inside the directive context.
function expression has to return a object for angularjs to identity it as a valid directive. at line 22 setting directive restrict to just as attribute, defining a link method, link method is mostly used when directive has DOM manipulation, link method takes three arguments,
scope : angularjs scope object
element : its a element object of directive matched (jqlite wrapped object)
attrs : attributes on element as key-value pair or hash.
code inside the sliderLink method should be pretty simple, using the jqlite element object to carry out DOM manipulation, using the angularjs $interval service,(angularjs wrapper for the setInterval method) to set timeout before text is changed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | angular.module('ngtextSlider',[]).directive('textSlider',function($interval){ //implementing a link function function sliderLink(scope,ele,attr){ if(ele.find('p').length == 0) return; ele.find('p').css('display','none'); var first = ele.find('p')[0]; first.style.display = "block"; var count = 1; $interval(function(){ ele.find('p').css('display','none'); var item = ele.find('p')[count]; item.style.display = "block"; count++; if(count >= ele.find('p').length){ count = 0; } },5000); }; return { restrict: 'A', //restrict directive to only attribute link:sliderLink // linking function }; }); |
example above is fairly simple directive in angularjs. many complex functionality can be implemented which i will be blogging as i come cross those topics.
please leave a comment help me learn and blog more effectively
happy coding.....
No comments:
Post a Comment