{"id":53,"date":"2012-11-18T09:37:56","date_gmt":"2012-11-18T09:37:56","guid":{"rendered":"http:\/\/ramandv.com\/blog\/?p=53"},"modified":"2013-07-04T08:31:49","modified_gmt":"2013-07-04T08:31:49","slug":"angular-js-sharing-data","status":"publish","type":"post","link":"http:\/\/www.ramandv.com\/blog\/angular-js-sharing-data\/","title":{"rendered":"Angular JS : Sharing data"},"content":{"rendered":"\n<!-- Quick Adsense WordPress Plugin: http:\/\/quickadsense.com\/ -->\n<div class=\"e9e85ee105af8a6a4a383deebf1fa216\" data-index=\"1\" style=\"float: none; margin:10px 0 10px 0; text-align:center;\">\n<script type=\"text\/javascript\"><!--\r\ngoogle_ad_client = \"ca-pub-4917982260456644\";\r\n\/* ramandv.com-ad1 *\/\r\ngoogle_ad_slot = \"9226290554\";\r\ngoogle_ad_width = 728;\r\ngoogle_ad_height = 90;\r\n\/\/-->\r\n<\/script>\r\n<script type=\"text\/javascript\"\r\nsrc=\"http:\/\/pagead2.googlesyndication.com\/pagead\/show_ads.js\">\r\n<\/script>\n<\/div>\n<p>In many scenarios, the data needs to be shared between different scopes. There are different ways to share the data among the scopes. The proper one can be chosen based on the need.<\/p>\n<p><strong>1. Sharing data between Parent scope and Child scope<\/strong><\/p>\n<p>If Parent-Child relationship can be established, then the data sharing can be implemented as follows.<\/p>\n<p>In AngularJS, Scopes inherits prototypically. ie. In simple terms, if the property is not defined in the child scope, it will be accessed from the parent&#8217;s scope. The parent scope&#8217;s member variable can be accessed by &#8220;$scope.$parent&#8221; property from child&#8217;s scope.<\/p>\n<p><em>Javascript<\/em><\/p>\n<pre><code>function Parent($scope) {\n    $scope.x= 5;\n    $scope.y= 5;\n}\n\nfunction Child($scope) {\n    $scope.modifyBothScopes= function() {\n       $scope.$parent.x++;\n    };\n    $scope.modifyonlyChildscope= function() {\n       \/\/ member \"y\" will be created in the child scope\n       \/\/ So, after the following statment,  $scope.$parent.y++  will only increment the parent scope. \n       \/\/ It would not affect the child scope.\n       $scope.y++;\n    };\n\n}\n<\/code><\/pre>\n<p><em>Html<\/em><\/p>\n<pre><code>&lt;div ng-controller=\"Parent\"&gt;\n    parentX = {{x}} &lt;br\/&gt;\n    parentY = {{y}}&lt;br\/&gt;\n&lt;div ng-controller=\"Child\"&gt;\n    childX = {{x}}&lt;br\/&gt;\n    childY = {{y}}&lt;br\/&gt;\n    &lt;a ng-click=\"modifyBothScopes()\"&gt;modifyBothScopes&lt;\/a&gt;&lt;br&gt;\n    &lt;a ng-click=\"modifyonlyChildscope()\"&gt;modifyonlyChildscope&lt;\/a&gt;\n&lt;\/div&gt;\n&lt;\/div&gt;\u200b\n<\/code><\/pre>\n<p><strong>JS Fiddle<\/strong><\/p>\n<p><a href=\"http:\/\/jsfiddle.net\/ramandv\/JHwxP\/\" title=\"http:\/\/jsfiddle.net\/ramandv\/JHwxP\/\">http:\/\/jsfiddle.net\/ramandv\/JHwxP\/<\/a><\/p>\n<p><strong>2. Sharing data using Service [like a global variable]<\/strong><\/p>\n<p>To share the data among independent controllers, Services can be used. Create a service with the data model that needs to be shared. Inject the service in the respective controllers.<\/p>\n<p>In the following example, Service is used to store the variable x. The independent controllers will check the value of X whenever needed.<\/p>\n<p><em>Javascript<\/em><\/p>\n<pre><code>angular.module('myApp', [])\n    .service('myService', function () {\n        var x=5 ;\n        return {\n            increase : function() {\n                x++;\n            },\n            getX : function() {\n                return x;\n            }\n       };\n    })\n\nfunction ControllerA($scope, myService) {\n    $scope.x = 1;\n    $scope.incrementDataInService= function() {\n        myService.increase();\n    }\n    $scope.syncDataWithService= function() {\n        $scope.x = myService.getX();\n    }        \n}\n\nfunction ControllerB($scope, myService) {\n   $scope.x = 1;\n    $scope.incrementDataInService= function() {\n        myService.increase();            \n    }\n    $scope.syncDataWithService= function() {\n        $scope.x = myService.getX();\n    }    \n}\u200b\n\u200b\n<\/code><\/pre>\n<p><em>HTML<\/em><\/p>\n<pre><code>&lt;div ng-app=\"myApp\"&gt;\n    &lt;div ng-controller=\"ControllerA\"&gt;\n        ControllerA.X = {{x}}&lt;br\/&gt;\n        &lt;a ng-click=\"incrementDataInService()\"&gt;incrementDataInService&lt;\/a&gt;&lt;br&gt;     \n        &lt;a ng-click=\"syncDataWithService()\"&gt;syncDataWithService&lt;\/a&gt;&lt;br&gt;           \n    &lt;\/div&gt;\n    &lt;hr\/&gt;\n    &lt;div ng-controller=\"ControllerB\"&gt;\n        ControllerB.X = {{x}}&lt;br\/&gt;\n        &lt;a ng-click=\"incrementDataInService()\"&gt;incrementDataInService&lt;\/a&gt;&lt;br&gt;     \n        &lt;a ng-click=\"syncDataWithService()\"&gt;syncDataWithService&lt;\/a&gt;&lt;br&gt;   \n    &lt;\/div&gt;\n&lt;\/div&gt;\n\u200b\u200b\n<\/code><\/pre>\n<p><strong>JS Fiddle<\/strong><\/p>\n<p><a href=\"http:\/\/jsfiddle.net\/ramandv\/kR859\/\" title=\"Angular JS sharing data using service\">http:\/\/jsfiddle.net\/ramandv\/kR859\/<\/a><\/p>\n<p><strong>3. Sharing data using Service &#8211; monitor the changes<\/strong><\/p>\n<p>In some times, it is important to monitor the changes in the service. AngularJS provides &#8220;$broadcast&#8221; to broadcast the data to the listening subscribers.<\/p>\n<p>The following contrived example shows the usage of $broadcast. The ControllerA and ControllerB subscribed to the event &#8220;XChanged&#8221;. The service &#8220;myService&#8221; will broadcast the event &#8220;XChanged&#8221; when the value of &#8220;x&#8221; changes.<\/p>\n<p><em>Javascript<\/em><\/p>\n<pre><code>angular.module('myApp', [])\n    .service('myService',  function ($rootScope) {\n        var x=5 ;\n        return {\n            increase : function() {\n                x++;\n                $rootScope.$broadcast('XChanged', x);\n            }\n       };\n    })\n\nfunction ControllerA($scope, myService) {\n    $scope.x = 1;\n    $scope.incrementDataInService= function() {\n        myService.increase();\n    }     \n    $scope.$on('XChanged', function(event, x) {\n        $scope.x = x;\n    });        \n}\n\nfunction ControllerB($scope, myService) {\n   $scope.x = 1;\n    $scope.incrementDataInService= function() {\n        myService.increase();            \n    }\n    $scope.$on('XChanged', function(event, x) {\n        $scope.x = x;\n    });           \n}\u200b\n\u200b\n<\/code><\/pre>\n<p><em>HTML<\/em><\/p>\n<pre><code>&lt;div ng-app=\"myApp\"&gt;\n    &lt;div ng-controller=\"ControllerA\"&gt;\n        ControllerA.X = {{x}}&lt;br\/&gt;\n        &lt;a ng-click=\"incrementDataInService()\"&gt;incrementDataInService&lt;\/a&gt;&lt;br&gt;     \n    &lt;\/div&gt;\n    &lt;hr\/&gt;\n    &lt;div ng-controller=\"ControllerB\"&gt;\n        ControllerB.X = {{x}}&lt;br\/&gt;\n        &lt;a ng-click=\"incrementDataInService()\"&gt;incrementDataInService&lt;\/a&gt;&lt;br&gt;     \n     &lt;\/div&gt;\n&lt;\/div&gt;\n<\/code><\/pre>\n<p><strong>JS Fiddle<\/strong><\/p>\n<p><a href=\"http:\/\/jsfiddle.net\/ramandv\/25CVc\/\" title=\"Blog- AngularJS-Simple-service-with-broadcast\">http:\/\/jsfiddle.net\/ramandv\/25CVc\/<\/a><\/p>\n\n<div style=\"font-size: 0px; height: 0px; line-height: 0px; margin: 0; padding: 0; clear: both;\"><\/div>","protected":false},"excerpt":{"rendered":"<p>In many scenarios, the data needs to be shared between different scopes. There are different ways to share the data among the scopes. The proper one can be chosen based on the need. 1. Sharing data between Parent scope and &hellip; <a href=\"http:\/\/www.ramandv.com\/blog\/angular-js-sharing-data\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[7,6],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v17.0 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<meta name=\"description\" content=\"This post covers: Sharing data between Controllers using Services. Monitoring data changes using $broadcast. Parent Child scope protoypical inheritance,\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"http:\/\/www.ramandv.com\/blog\/angular-js-sharing-data\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Angular JS : Sharing data between Controllers | Parent Child scope\" \/>\n<meta property=\"og:description\" content=\"This post covers: Sharing data between Controllers using Services. Monitoring data changes using $broadcast. Parent Child scope protoypical inheritance,\" \/>\n<meta property=\"og:url\" content=\"http:\/\/www.ramandv.com\/blog\/angular-js-sharing-data\/\" \/>\n<meta property=\"og:site_name\" content=\"Articles for Developers\" \/>\n<meta property=\"article:published_time\" content=\"2012-11-18T09:37:56+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2013-07-04T08:31:49+00:00\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"ramandv\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"http:\/\/www.ramandv.com\/blog\/#website\",\"url\":\"http:\/\/www.ramandv.com\/blog\/\",\"name\":\"Articles for Developers\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"http:\/\/www.ramandv.com\/blog\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"http:\/\/www.ramandv.com\/blog\/angular-js-sharing-data\/#webpage\",\"url\":\"http:\/\/www.ramandv.com\/blog\/angular-js-sharing-data\/\",\"name\":\"Angular JS : Sharing data between Controllers | Parent Child scope\",\"isPartOf\":{\"@id\":\"http:\/\/www.ramandv.com\/blog\/#website\"},\"datePublished\":\"2012-11-18T09:37:56+00:00\",\"dateModified\":\"2013-07-04T08:31:49+00:00\",\"author\":{\"@id\":\"http:\/\/www.ramandv.com\/blog\/#\/schema\/person\/ca1ede7143462f244081566e6ff97658\"},\"description\":\"This post covers: Sharing data between Controllers using Services. Monitoring data changes using $broadcast. Parent Child scope protoypical inheritance,\",\"breadcrumb\":{\"@id\":\"http:\/\/www.ramandv.com\/blog\/angular-js-sharing-data\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"http:\/\/www.ramandv.com\/blog\/angular-js-sharing-data\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"http:\/\/www.ramandv.com\/blog\/angular-js-sharing-data\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Angular JS : Sharing data\"}]},{\"@type\":\"Person\",\"@id\":\"http:\/\/www.ramandv.com\/blog\/#\/schema\/person\/ca1ede7143462f244081566e6ff97658\",\"name\":\"ramandv\",\"url\":\"http:\/\/www.ramandv.com\/blog\/author\/ramandv\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"description":"This post covers: Sharing data between Controllers using Services. Monitoring data changes using $broadcast. Parent Child scope protoypical inheritance,","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"http:\/\/www.ramandv.com\/blog\/angular-js-sharing-data\/","og_locale":"en_US","og_type":"article","og_title":"Angular JS : Sharing data between Controllers | Parent Child scope","og_description":"This post covers: Sharing data between Controllers using Services. Monitoring data changes using $broadcast. Parent Child scope protoypical inheritance,","og_url":"http:\/\/www.ramandv.com\/blog\/angular-js-sharing-data\/","og_site_name":"Articles for Developers","article_published_time":"2012-11-18T09:37:56+00:00","article_modified_time":"2013-07-04T08:31:49+00:00","twitter_misc":{"Written by":"ramandv","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebSite","@id":"http:\/\/www.ramandv.com\/blog\/#website","url":"http:\/\/www.ramandv.com\/blog\/","name":"Articles for Developers","description":"","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"http:\/\/www.ramandv.com\/blog\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"WebPage","@id":"http:\/\/www.ramandv.com\/blog\/angular-js-sharing-data\/#webpage","url":"http:\/\/www.ramandv.com\/blog\/angular-js-sharing-data\/","name":"Angular JS : Sharing data between Controllers | Parent Child scope","isPartOf":{"@id":"http:\/\/www.ramandv.com\/blog\/#website"},"datePublished":"2012-11-18T09:37:56+00:00","dateModified":"2013-07-04T08:31:49+00:00","author":{"@id":"http:\/\/www.ramandv.com\/blog\/#\/schema\/person\/ca1ede7143462f244081566e6ff97658"},"description":"This post covers: Sharing data between Controllers using Services. Monitoring data changes using $broadcast. Parent Child scope protoypical inheritance,","breadcrumb":{"@id":"http:\/\/www.ramandv.com\/blog\/angular-js-sharing-data\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["http:\/\/www.ramandv.com\/blog\/angular-js-sharing-data\/"]}]},{"@type":"BreadcrumbList","@id":"http:\/\/www.ramandv.com\/blog\/angular-js-sharing-data\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Angular JS : Sharing data"}]},{"@type":"Person","@id":"http:\/\/www.ramandv.com\/blog\/#\/schema\/person\/ca1ede7143462f244081566e6ff97658","name":"ramandv","url":"http:\/\/www.ramandv.com\/blog\/author\/ramandv\/"}]}},"jetpack_featured_media_url":"","jetpack_publicize_connections":[],"jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p6YZCe-R","_links":{"self":[{"href":"http:\/\/www.ramandv.com\/blog\/wp-json\/wp\/v2\/posts\/53"}],"collection":[{"href":"http:\/\/www.ramandv.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.ramandv.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.ramandv.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/www.ramandv.com\/blog\/wp-json\/wp\/v2\/comments?post=53"}],"version-history":[{"count":9,"href":"http:\/\/www.ramandv.com\/blog\/wp-json\/wp\/v2\/posts\/53\/revisions"}],"predecessor-version":[{"id":148,"href":"http:\/\/www.ramandv.com\/blog\/wp-json\/wp\/v2\/posts\/53\/revisions\/148"}],"wp:attachment":[{"href":"http:\/\/www.ramandv.com\/blog\/wp-json\/wp\/v2\/media?parent=53"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.ramandv.com\/blog\/wp-json\/wp\/v2\/categories?post=53"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.ramandv.com\/blog\/wp-json\/wp\/v2\/tags?post=53"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}