Friday, February 1, 2013

AngularJS -- Customize ngRepeat with a custom Directive

Actually we are not going to use ngRepeat here; we will be populating a <dl> tag with <dt> and <dd>
...

==== Step 01 - create a widge.product.details.js  =====

// binds to $scope.details = [] //array object


angular.module('widget.product.details',[])
.directive('productDetails',function(){
return {
template:'<dl class="dl-horizontal"></dl>',
replace:true,
restrict:'E',
compile : function compile(tElement, tAttrs, transclude) {
return {
post: createProductDetails
}
}
}
});


var createProductDetails = function (scope, iElement, iAttrs, controller) {
scope.$watch('details', function(newVal, oldVal) {
angular.forEach(newVal, function(v,k){
iElement.append( angular.element('<dt>'+v.dt+'</dt><dd>'+v.dd+'</dd>') );
});
});
}


==== Step 02 - create your html =====

<div class="span7" ng-controller="ProductInfoCtrl">
<product-details></product-details>
</div>

==== Step 03 - create a app.product.js =====

function ProductInfoCtrl($scope) {
$scope.details = [
                 {dt:'condition',dd:'brand new'},
                 {dt:'year bought',dd:'3 years ago'},
                 ]
}