How to create a factory or service to share data between controllers in angularJS

<div ng-app="serviceApp" ng-controller="Controller1">
    <p>Controller 1: {{ sharedService.data }}</p>
</div>

<div ng-app="serviceApp" ng-controller="Controller2">
    <p>Controller 2: {{ sharedService.data }}</p>
</div>

<script>
    var app = angular.module('serviceApp', []);
    app.factory('sharedService', function() {
        return {
            data: 'Shared Data'
        };
    });

    app.controller('Controller1', function($scope, sharedService) {
        $scope.sharedService = sharedService;
    });

    app.controller('Controller2', function($scope, sharedService) {
        $scope.sharedService = sharedService;
    });
</script>

 

Post your Answer