How to share data between two controllers using AngularJS factory service

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


(function () {
   'use strict';

      .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) { 

         return service; 

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

         function _addItem() { 

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



<!DOCTYPE html>
<html lang="en-US">
    <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 ng-controller="SecondController as vm">
                <li ng-repeat="item in vm.itemsToDisplay">{{item}}</li>

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


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. 



About author

User avatar

Waqas Anwar

Founder of, Senior Consultant, Microsoft .NET and Web Technologies