AngularJS Live Example

by Djul

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://code.angularjs.org/1.0.6/angular-resource.js"></script>
<div ng-controller = "companiesCtrl"> 
  	  <ul ng-repeat="company in companies">
         <li>{{company}}</li>
  	  </ul>
</div>

JavaScript

var serviceDataCaching = angular.module('myModule', ['ngResource']);

serviceDataCaching.$inject = ['$scope', 'Data'];

serviceDataCaching.service('companiesSrv', ['$q', '$timeout', function($q, $timeout){
	var self = this;
  
  var httpResult = [
  	'company 1',
    'company 2',
    'company 3'
  ];
  
  this.companies = ['company preloaded'];
  this.getCompanies = function() {
    var deferred= $q.defer();
    $timeout(function(){
    	// keep the array object reference!!
      self.companies.splice(0, self.companies.length);
      
      //if you use the following code
			// self.companies = [];
      // the controller will loose the reference to the array object as we are creating an new one
      // as a result it will no longer get the cahnges made here!
			for(var i=0; i< httpResult.length; i++){
      	self.companies.push(httpResult[i]);
      }
      deferred.resolve();    
    }, 3000);                    
    return deferred.promise;
  }
}]);   

serviceDataCaching.controller('companiesCtrl', function ($scope, companiesSrv) {
		$scope.companies = companiesSrv.companies;
    companiesSrv.getCompanies();
});