How to share data between two controllers using AngularJS factory service

Waqas Anwar
17 February 2016
2142 Views

If you have two different controllers and you want to share common data between them you can use AngularJS factory services to share data.

AngularJS

(function () {
   'use strict';

    angular
      .module('app', [])
      .factory('SharedService', SharedService)
      .controller('FirstController', FirstController)
      .controller('SecondController', SecondController);

      function SharedService (){
         var vm = this;
         vm.items = ['Black', 'White', 'Red', 'Green', 'Blue'];
         var service = {
            getItems: _getItems,
            addItem: _addItem
         };

         function _getItems() {
            return vm.items;
         }

         function _addItem(item) {
            vm.items.push(item);
         }

         return service;
      }

      FirstController.$inject = ['SharedService'];
      function FirstController (SharedService){
         var vm = this;
         vm.item = "";
         vm.addItem = _addItem;

         function _addItem() {
            SharedService.addItem(vm.item);
         }
      }

      SecondController.$inject = ['SharedService'];
      function SecondController (SharedService){
         var vm = this;
         vm.itemsToDisplay = SharedService.getItems();
      }

})();

HTML

<!DOCTYPE html>
<html lang="en-US">
   <head></head>
<body ng-app="app">

<div ng-controller="FirstController as vm">
   Item: <input type="text" ng-model="vm.item" />
   <input type="button" value="Add" ng-click="vm.addItem()" />
</div>

<div ng-controller="SecondController as vm">
   <ul>
      <li ng-repeat="item in vm.itemsToDisplay">{{item}}</li>
   </ul>
</div>

<script src="angular.min.js"></script>
<script src="app.js"></script>

</body>
</html>

As you can see in the above code that array of items is defined in SharedService and two different controllers have access to the same array of items. FirstController is adding item in the array and SecondController is displaying items from the SharedService.