AngularJS custom-repeat
HTML
<script src="http://ci.angularjs.org/view/AngularJS/job/angular.js-angular-master/lastSuccessfulBuild/artifact/build/angular.js"></script>
<script type="text/ng-template" id="customRepeat.html">
<div>
<div custom-repeat-new-scope>
<div class="custom-repeat-item">
{{ item.id }}
<br/>
<span transclude-extended="customRepeatScope.transclude"></span>
</div>
</div>
</div>
</script>
<div ng-controller="MainController">
<custom-repeat items="items">
{{ text }}
<br/>
{{ item.name }}
</custom-repeat>
<button ng-click="updateProperty()">Update property</button>
<button ng-click="updateItems()">Update items</button>
</div>
CSS
.custom-repeat-item {
border: 1px solid black;
margin-bottom: 10px;
}
JavaScript
var app = angular.module('myApp', []);
app.controller("MainController", function ($scope) {
$scope.text = "Hello world";
$scope.items = [{
id: 1,
name: "one"
}, {
id: 2,
name: "two"
}, {
id: 3,
name: "three"
}];
$scope.updateProperty = function () {
$scope.items[1].name = "dos";
};
$scope.updateItems = function () {
$scope.items = [{
id: 1,
name: "once"
}, {
id: 2,
name: "doce"
}, {
id: 3,
name: "trece"
}];
};
});
app.directive("customRepeat", function () {
return {
restrict: "E",
transclude: true,
templateUrl: "customRepeat.html",
scope: {
items: "="
},
controller: function ($scope) {
this.scope = $scope;
},
link: function (scope, element, attrs, controllers, transclude) {
scope.transclude = transclude;
}
};
});
app.directive("customRepeatNewScope", function ($compile) {
return {
restrict: "A",
require: "^customRepeat",
link: function (scope, element, attrs, customRepeat) {
var transcludedScope = customRepeat.scope.$parent.$new();
element.data("$scope", transcludedScope);
transcludedScope.customRepeatScope = customRepeat.scope;
element.children().attr("ng-repeat", "item in customRepeatScope.items track by item.id");
$compile(element.children())(transcludedScope);
}
};
});
app.directive("transcludeExtended", function () {
return {
link: function (scope, element, attrs) {
var transclude = scope.$eval(attrs.transcludeExtended);
if (transclude) {
transclude(scope, function (clone, childScope) {
element.append(clone);
});
}
}
};
});