/** * Created by nmeegama on 8/27/16. */ /************ Controller to set the data *******************/ (function (angular) { 'use strict'; angular.module('MyApp').controller('SetDataCtrl', [ '$scope', 'MyService', function ($scope, MyService) { $scope.setData = function (data) { MyService.setData(data); }; }]); })(angular); /************ Controller to get the data *******************/ (function (angular) { 'use strict'; angular.module('MyApp').controller('GetDataCtrl', [ '$scope', 'MyService', function ($scope, MyService) { $scope.data = MyService.getData(); }]); })(angular); /************ Service to pass the data *******************/ (function (angular) { 'use strict'; angular.module('MyApp').service('MyService', function () { var data = ''; var setData = function (data) { data = data; }; var getData = function () { return data; }; return { setData: setData, getData: getData }; }); })(angular);
HTML
<!DOCTYPE html> <html lang="en" ng-app="MyApp"> <head> <meta charset="UTF-8"> <title>My angular app</title> <script src="include-js-files-here.js"></script> </head> <body> <!-- setting the data initially --> <div ng-controller="SetDataCtrl" data-ng-init="setData('Hello world')"> ..... <!-- Below we set the getData COntroller to get the above data set --> <div ng-controller="GetDataCtrl"> <!-- printing the data --> {{data}} </div> ..... </div> </body> </html>