I'm new to angular and am trying to accomplish a very simple task, which doesn't seem to be that simple in angular.
I am having some data (just a variable named var1 for simplicity), that I'm modifying in one area of the webpage while I want to display it in another area of the webpage.
<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>
//..
And I am initializing the variable in the corresponding controller:
angular.module('app', [])
.controller('TestCtrl', function($rootScope){
$rootScope.var1 = 1;
$rootScope.var2 = 2;
this.updateValues = function() {
srv.updateValues($rootScope.var1, $rootScope.var2);
};
});
Now, as you probably know, the second time I attach the ng-controller
to a div, I get a completely new instance of the controller which knows nothing about the first instance where I actually modified the data.
So how can I access the var1
of the first controller, in another area of the webpage?
https://plnkr.co/edit/XgIWFW89tavnjOW09TBp?p=preview
One thing which comes to my mind, would be to attach the
TestCtrl
to the body so that basically the whole website has only one instance of theTestCtrl
. Is this a common approach? I already feel that 90% of my controllers will be attached to the body tag.I already read the suggestion of using services and to be honest, I don't really see how such a service should be implemented for such a simple scenario.
Is there another solution?