Saturday 5 April 2014

Angular ng-repeat in directive

Here I am going to explain how to create a directive for displaying a dynamic content.

Directive

 
angular.module('samplemodule').directive('itemList',
function() {
return {
 restrict : "AC",
 template : '<div>'
  + '<div>{{ datalist.title }}</div>'
  + '<div>{{ datalist.content }}</div>'
  + '</div>',
 link : function(scope, elm, attrs) {
  scope.$watch(attrs.itemList, function(value) {
   elm.text(value);
  });
 }
};
}
);
 

Directives are markers on a DOM element that tell AngularJS's HTML compiler to attach a specified behavior to that DOM element or even transform the DOM element and its children. Better define all Global controllers in Directives. Ex: Warning message, alert etc.

'A' - Attribute (Use it as <div itemList>)

'E' - Element (Use it as <itemList>)

'C' - Class. (Use it as <div class="itemList">)

'M' - Comment (Use it as <!- directive: itemList -> )

We used watch concept in directive .Watch is a powerful feature of angular js. “$watch” concept in Angular is to observe the changes on the data of the scope from the controller. That is controller can add a listener on an attribute of its scope.

Controller

 
 
 $scope.datalist = data //  json from service
 
 

View

 
 
<div class="item-list:list" data-ng-repeat="datalist in datalists">
 
 

Related Posts

1. Client side pagination using angular js

2. Angular flash message using directive

3. Angular routing

4. Rating Stars using angular js Directive concept

5. Communication between factory file and controller in Angular js

6. Communicate with controllers in angular js


No comments :

Post a Comment