Injecting Service to Directives in AngularJs

Injecting Service to Directives in AngularJs










Demo on Plnkr - http://plnkr.co/edit/nLcYQ69OhgVWHo74CuVT?p=preview

index.html
<!DOCTYPE html>
<html ng-app="EOneApp">

  <head>
    <meta charset="utf-8" />
    <title>Injecting Service to Directives in AngularJs</title>

    <link rel="stylesheet" href="style.css" />
   
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script src="raphael.min.js"></script>
    <script src="morris.min.js"></script>
    <script src="app.js"></script>
    <script src="chartangular.js"></script>
    </head>

  <body ng-controller="connectionSummaryController">
       <linechart id="line-example" data-options="chart_options"></linechart>
  </body>

</html>
chartangular.js

eOneapp.directive('linechart', ['$compile', 'connectionService',
  function($compile, connectionService) {

    function createChart(el_id, options) {
      connectionService.getSubscriberLastWeek().then(function(resp) {
        options.data = resp.data;
        options.element = el_id;
        var r = new Morris.Line(options);

        return r;
      });
    }

    return {
      restrict: 'E',
      scope: {
        //options: '='
      },
      replace: true,
      template: '<div></div>',
      link: function(scope, element, attrs) {
        scope.options = {
          data: [],
          xkey: 'RegistedDay',
          ykeys: ['SubscriberRegisted'],
          labels: ['Subscriber'],
          parseTime: false
        };

        return createChart(attrs.id, scope.options)
      }
    }

  }
]);

app.js

 var eOneapp = angular.module('EOneApp', []);

 eOneapp.service("connectionService", function myfunction($http) {

   this.getSubscriberLastWeek = function() {

     return $http({
       method: 'GET',
       url: 'http://private-634da8-test11074.apiary-mock.com/SubscriberByWeek'
     });

   };

 });

 eOneapp.controller('connectionSummaryController', function($scope, connectionService) {
   $scope.chart_options = {
     data: [],
     xkey: 'RegistedDay',
     ykeys: ['SubscriberRegisted'],
     labels: ['Subscriber'],
     parseTime: false
   };
 });
Previous
Next Post »
Thanks for your comment