I found nice looking "console like" window - http://demos.telerik.com/kendo-ui/autocomplete/events (start typing in box) and I'm trying to create Angular version.
My code looks like this:
angular.module('myApp', [])
.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}}</div>',
'</div>'
].join(''),
link: function($scope, element) {
$scope.events = [];
$rootScope.$on('Log', function(event, data) {
//console.log(event, data);
$scope.events.splice(0, 0,{
type: 'log',
data: "Log :: "+data
});
});
$rootScope.$on('Error', function(event, data) {
//console.log(event, data);
$scope.events.splice(0, 0,{
type: 'error',
data: "Error :: "+data
});
});
}
};
And I can add item to my console by calling:
$rootScope.$emit("Error", "Something bad happened");
Here is my current version: https://plnkr.co/edit/iLZKa8hPCBSRDV0dhn15?p=preview
On top is original jQuery version, on bottom in Angular version.
The thing I'm missing is event aggregation:
Original version is groupping entries and adding counter is same event occures more that once.
How can I add this to my code (Angular way)?
Besides conversion I have two more questions I'd like to ask:
-This in one of my first directives I'm writing, if I'm making any mistakes in it please let me know.
-This "console" will show many events and I'd like to know how to optimize it - should I show for example only last 20 entries or can I add functionality like virtual scroll to optimize it a bit?
1 Answer 1
I've managed to add counter to events. This is my version of code:
angular.module('myApp', [])
.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 with demo.
I can add entry from anywhere using:
$rootScope.$emit("Error", "Something bad happened");
Hopefully someone will find it useful.