I am relatively new to using Angular and I am facing a challenge with a seemingly simple task that is proving to be more complex within the framework.
The issue at hand involves data manipulation, specifically with a variable named var1. I am modifying this data in one section of the webpage while needing to display it in another section.
<body ng-app="app">
<div id="div1" ng-controller="TestCtrl">
<input type="text" ng-model="var1" /> Var1: {{ var1}}
</div>
<br />
<div id="div2" ng-controller="TestCtrl">
Var1: {{ var1 }}
</div>
//..
I have initialized the variable within the controller as follows:
angular.module('app', [])
.controller('TestCtrl', function($rootScope){
$rootScope.var1 = 1;
$rootScope.var2 = 2;
this.updateValues = function() {
srv.updateValues($rootScope.var1, $rootScope.var2);
};
});
The issue arises when attaching the ng-controller
to multiple divs, creating separate instances of the controller. This results in the second instance not recognizing the data modifications made in the first instance.
How can I access the var1
value from the first controller in another section of the webpage?
https://plnkr.co/edit/XgIWFW89tavnjOW09TBp?p=preview
One potential solution that comes to mind is attaching the
TestCtrl
to the body, ensuring only one instance of the controller exists for the entire webpage. Is this a common practice? It seems like a majority of my controllers may end up attached to the body tag.I have come across the suggestion of using services, however, I am struggling to see how to implement a service for this specific scenario.
Are there any other solutions available?