AngularJS Tutorial - Use loop in directive replacement








The following code shows how to use loop in directive replacement.

Example


<!doctype html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<script type='text/javascript'>
angular.module('myApp', [])
    .controller("TestCtrl", function ($scope) {
    $scope.items = [1, 2, 3, 4];<!--  w  w w  .  j ava  2s . co  m-->
})
.directive('row', function ($compile) {
    return {
        restrict: 'E',
        scope: {
            items: "="
        },
        link: function (scope, element, attrs) {
            var html ='<div ng-repeat="item in items">{{item}}</div>';
            var e =$compile(html)(scope);
            element.replaceWith(e);
        }
    };
});
</script>
</head>
<body ng-app="myApp">
  <div ng-controller="TestCtrl" ng-app="myApp">
    <row items="items">***</row>
</div>
</body>
</html>

The code above is rendered as follows: