AngularJS - $compile and scopes
by Sunny SM
HTML
<div ng-controller="AngularCtrl">
<div my-repeater items='items'></div>
</div>
CSS
.important {
color: red;
}
.ng-scope { border: 1px solid red; margin: 2px}
JavaScript
var myApp = angular.module('myApp', []);
myApp.directive('myRepeater', function($compile, $rootScope) {
return {
restrict: 'A',
scope: {
items: '=items'
},
link: function(scope, element, attrs) {
// create an outer, "top level" element/div
// so that Angular will only create one new scope
var mainTpl = '<div>';
var lineTpl = "<div ng-click='updateRating(items[?])' ng-class='getRatingClass(items[?].ratings)'>{{items[?].ratings}}</div>";
scope.updateRating = function(item) {
item.ratings = item.ratings + 1;
};
scope.getRatingClass = function(rating) {
if (rating > 10) {
return 'important';
}
return 'normal';
};
for (var i = 0; i < scope.items.length; i++) {
mainTpl += lineTpl.replace(/\?/g, i);
}
mainTpl += '</div>';
element.replaceWith($compile(mainTpl)(scope));
}
};
});
function AngularCtrl($scope) {
$scope.items = [{
id: 1,
ratings: 10},
{
id: 2,
ratings: 20},
{
id: 3,
ratings: 0}];
}