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);

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><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);

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:
from some answers here


Popular posts from this blog

Asp.Net Ending Response options, Response.End() vs CompleteRequest()

c# Service Play Sound with NAudio example by Moshe

MatDatePicker Errors