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.
<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
}
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.