I've asked question on SO how to rewrite jQuery code to Angular. Because I got no answers I've tried to create something by my own. This is my version of code:
(function() {
'use strict';
angular
.module('misiu.directives', [])
.directive('console', ['$rootScope', function($rootScope) {
return {
restrict: 'E',
template: [
'<div class="console animated">',
'<div ng-repeat="event in events" ng-class="{\'error\': event.type == \'error\', \'log\': event.type == \'log\'}">',
'{{event.data}}<span ng-if="event.count>1" class="count">{{event.count}}</span>',
'</div>',
'</div>'
].join(''),
link: function($scope, element) {
$scope.events = [];
$rootScope.$on('Log', function(event, data) {
if ($scope.events[0] !== undefined && $scope.events[0].type === "log" && $scope.events[0].data === "Log :: " + data) {
$scope.events[0].count++;
} else {
$scope.events.splice(0, 0, {
type: 'log',
data: "Log :: " + data,
count: 1
});
}
});
$rootScope.$on('Error', function(event, data) {
if ($scope.events[0] !== undefined && $scope.events[0].type === "error" && $scope.events[0].data === "Error :: " + data) {
$scope.events[0].count++;
} else {
$scope.events.splice(0, 0, {
type: 'error',
data: "Error :: " + data,
count: 1
});
}
});
}
};
}])
})();
and Plunker showing demo (move mouse over console div to add entries)
Because this is my first directive I'd like to ask for code review.
I'm adding new items to my console using one of those lines:
$rootScope.$emit("Log", "Something");
$rootScope.$emit("Error", "Terrible error");
I must add $rootScope as dependency to every controller if I want to use my directive there. Maybe factory would be better? This way I could for example add a way to remove everything except last 20 entries.
I'd like my directive to be optimized for speed. I've tested it for a while, but I'm not sure I did everything properly.
I need only single way binding and the thing that can change it only top most element (counter can increase), rest of element don't need binding. Maybe this can be also optimized.
Any other comments on what is wrong are welcome.
EDIT
I've created another code review request that includes same control, but using provider.