Wednesday, August 7, 2013

AngularJS create directive with ng-repeat example

Bresleveloper's AngularJS tutorial: Directive :)

goooooo Angular!!!
there r still no simple tutorials about angular's bit more advanced stuff so i'll share my part and today about directives.
so basically a directive is all the "ng-xxx" attrs, meaning that they have a JS function that tells them what to do with the specific HTML element.

so the most basic thing u can do it this:
<span myboldme>bla bla</span>
and in the js
myModule.directive("myboldme", function ($compile) {
  return function (scope, element, attrs) {
    var b = "<b></b>"
    var boldElem = angular.element(b);
       boldElem.text(element.text());
    $compile(boldElem)(scope);
    element.replaceWith(boldElem);
  }
});
 

and u get <b>bla bla</b>.
YEP!! all those element given by angular r JQuery objects :)

now my case was doing ng-repeat over 2 element, and yes u can take the unstable version and use ng-repeat-start but I wanted the stable version so I jumped on the opportunity to create a directive.
my thing was iterating these 2:
<li><span>&nbsp;</span><li>
<li><a href="#">{{ myValue }}</a><li>

took some time to find all the twicks but in the end I got myself to creating just a funny tag like this:
<myHtmlTag mydirective ng-repeat="item in items"></myHtmlTag> (o.c. u can just do <li...)
and the directive looks like this:

myModule.directive("mydirective", function ($compile) {
  return function (scope, element, attrs) {
    var LIs = '';
    for (var i = 0; i < scope.items.length ; i++) {
      LIs += "<li><span>&nbsp;</span></li><li><a href=\"#\">" + scope.items[i] + "</a></li>"
    }
 
   var newElements = angular.element(LIs);
    $compile(newElements)(scope);
    element.replaceWith(newElements);
  }
});
 


some overview:
scope is the usual $scope, and in order to have the items array I had to put the ngRepeat attr. the rest is clear and there is much to learn about all these stuff.

here is a more advanced example: http://jsfiddle.net/vittore/LzRwj/
from some answers here http://stackoverflow.com/questions/16900050/angular-js-ng-repeat-across-multiple-elements

No comments:

Post a Comment