AngularJS : basic run function block illustrated

AngularJS : basic run function block illustrated Any code that needs to run when an application starts should be declared in a factory, exposed through a function, and injected into the application .run block.

by Daan De Smedt

HTML

<div ng-app="app" ng-controller="BasicController as vm">
  The application is loaded, and the <pre style="display:inline;">.run</pre> block initializes the <pre style="display:inline;">DataService</pre>. Call the <pre style="display:inline;">Get data</pre> button to see that the initialize has done it's job.
  <br/><br/>
  <button ng-click="vm.getData()">Get data</button>
</div>

JavaScript

angular
    .module('app', [])
    .controller('BasicController', BasicController)
    .factory('DataService', DataService)
    .run(runBlock)

// run block 
runBlock.$inject = ['DataService'];
function runBlock(DataService) {
    DataService.initialize({
    	restUrl: 'http://api-url.com/api/'
    });
}

// basic controller
BasicController.$inject = ['DataService'];
function BasicController(DataService) { 
  var vm = this;
  vm.getData = getData;
  
  function getData(){
  	DataService.getData();
  }
}

// data service
function DataService(){
	var restUrl;
	
	return {
    initialize: initialize,
    getData: getData
  }
  
  function initialize(options){
  	console.log('Initialize data service, options - ', options);
    restUrl = options.restUrl;
  }
  
  function getData(){
  	console.log('Getting data from rest url initialized in the application run block : ' + restUrl);
  	// get data logics
  }
  
}