Skip to main content
4 of 5
edited tags; edited title
200_success
  • 144.2k
  • 22
  • 188
  • 473

Simple console directive, revised using provider

I recently created my first directive based on jQuery plugin and I asked for review here: Angular console like window - first directive

I've edited my directive so now instead of $rootScope it uses provider.
Below is my code:

(function() {
  'use strict';

  angular
    .module('misiu.providers', [])
    .provider('simpleConsole', function() {

      var events = [];
      var separator = '::'; //default

      //public methods
      this.$get = function() {
        return {
          addLog: function(data) {
            addEvent('log', 'Log' + separator + data);
          },
          addError: function(data) {
            addEvent('error', 'Error' + separator + data);
          },
          clear: function() {
            events.length = 0;
          },
          events: events
        };
      };

      //private method
      var addEvent = function(type, data) {
        if (events.length > 0 && events[0].type === type && events[0].data === data) {
          events[0].count++;
        } else {
          events.unshift({
            type: type,
            data: data,
            count: 1
          });
        }
      };

      //this is available only in config
      this.setSeparator = function(value) {
        separator = value;
      };
    });

  angular
    .module('misiu.directives', ['misiu.providers'])
    .directive('simpleConsole', ['simpleConsole', function(simpleConsole) {
      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 = simpleConsole.events;
        }
      };
    }]);
})();

and Plunker to see results.

I'd like to ask for review. Especially that provider part, because I'm not sure if all functions in it are correctly declared - private methods should be private, setSeparator should be available only in config section and addLog,addError should be the only two public methods available inside controllers and directives.

Any other general tips are welcome.

Misiu
  • 349
  • 1
  • 5
  • 15