How to create Angular Factory and How to share data between controllers

angular
factory
shareddata
module

#1
  1. Create a separate javascript file. For example:

    yourApp\js\modules\my-module.js

  2. Put a module inside my-module.js

    angular.module('myServices',[])

  3. Connect my-module.js in the yourApp\WEB-INF\pages\header.library.ftl :

    <script src="js/modules/my-module.js"></script>

  4. Connect myServices to your application yourApp\WEB-INF\pages\header.script.init.ftl

    customAngularModules.push('myServices');

  5. Create a factory in myServices module:

     angular.module('myServices',[])
     .factory('sharedDataFactory', function(){
         var someObj ={};
         function get(){
              return someObj;
         }
         function set(newObj){
            someObj = newObj;
         }
    
       return {
         get: get,
         set: set
         };
     });
    
  6. Use Factory in controller:

A. inject sharedDataFactory in controller

app.controller('myAwesomePageCtrl',
    ['$scope', '$rootScope','sharedDataFactory',
    function($scope, $rootScope,sharedDataFactory) {
   //your controller logic
}]);

B. set the data

   var myObj = {'Year':'2010', 'Month':'Jan', 'Page': 'myreports\awesomedashboard'};
   sharedDataFactory.set({myObject:myObj});

C. get the data

  //have fun
   var myFactoryObj = sharedDataFactory.get();

This approach I have used for Sydney TM1 Conference app. Instead of Factory you can use Service. It’s some deference between Service and Factory ( https://blog.thoughtram.io/angular/2015/07/07/service-vs-factory-once-and-for-all.html ).