AngularJS : rendering data from a service through a custom directive

AngularJS : rendering data from a service through a custom directive Illustrating seperation of data collection through a 'factory' provider using the public GitHub API and rendering this data through a custom directive.

by Daan De Smedt

HTML

<!-- 
  AngularJS : rendering data from a service through a custom directive
  Remove the data or reload the data to trigger the directive $destroy listener
-->

<!-- application container -->
<div ng-app="app" ng-controller="BasicController as vm">

  <!-- directive view template -->
  <script type="text/ng-template" id="views/user/github/info.html">
    <div>
      <img width="40px" height="40px" ng-src="{{user.avatar_url}}" />
      <span style="float:right;">
          {{::user.login}} 
          <span style="font-weight:bold;text-transform:uppercase;font-size:11px;color:gray;">
            | {{::user.type}}
          </span>
      </span>
    </div>
  </script>

  <b>GITHUB PUBLIC USERS</b>
  <br/><br/>
  <button ng-click="vm.reloadUsers()">Reload data</button>
  <button ng-click="vm.removeUsers()">Remove data</button>
  <br/><br/>
  <git-hub-user-info ng-repeat="user in vm.users track by $index"></git-hub-user-info>
</div>

JavaScript

angular
  .module('app', [])
  .factory('githubDataService', githubDataService)
  .controller('BasicController', BasicController)
  .directive('gitHubUserInfo', gitHubUserInfo)

/* directive */
function gitHubUserInfo() {
  var directive = {
    link: link,
    templateUrl: 'views/user/github/info.html',
    restrict: 'E'
  };
  return directive;
	  
  function link(scope, element, attrs) {
  	console.log('link');
    /* add clean-up listeren */
    element.on('$destroy', function() {
      console.log('directive $destroy event listeren');
      scope.$destroy();
    });
  }
  
}

/* controller */
function BasicController(githubDataService) {

  var vm = this;
  vm.users = [];
  vm.reloadUsers = reloadUsers;
	vm.removeUsers = removeUsers;
  
  init();

  function init() {
    return githubDataService.getUsers()
      .then(function(data) {
        vm.users = data;
      });
  }
  
  function reloadUsers(){
  	removeUsers();
  	init();
  }
  
  function removeUsers(){
  	vm.users = [];
  }

}

/* service */
function githubDataService($http) {
  return {
    getUsers: getUsers
  };

  function getUsers() {
    return $http.get('https://api.github.com/users')
      .then(getUsersComplete)
      .catch(getUsersFailed);

    function getUsersComplete(response) {
      return response.data;
    }

    function getUsersFailed(error) {
      console.log('XHR Failed for getAvengers.' + error.data);
    }
  }

}