Share Data Between Controllers Using Service Angularjs 1.6.1
Solution 1:
Since you are assigning the DataShareServ
to the scope of your gnomeList
Controller, you could simply iterate over the Data which is stored in your service and which gets updated and reassigned on every request. This way you don't have to deal with syncing your objects on different Controllers.
This way, the html would look something like this:
<ling-repeat="gnome in listCtrl.listServ.data">
{{gnome.name}}
</li>
Edit
Also note, you have another Problem in your Code. In the gnomeList
Controller, you are calling the request
method of your Service which does an async request to some endpoint and assigns its result to a local variable, but you do not wait with assigning your controller variable to the result of the Service variable. So in simple Words:
self.list = self.listServ.data;
this will always be empty because the http request is async. You need to deal with Promises (or something like that). Take a look at the $q
Service from angular: https://docs.angularjs.org/api/ng/service/$q
Note that this would not be important if you would go with my solution, just wanted to point that out.
Solution 2:
The obvious problem is that self.list
is being reassigned.
After self.list = response.data.entries
is done, self.list
and DataShareServ.data
refer to different objects.
It could be solved by keeping the reference to the same object with
self.list.length = 0;
Object.assign(self.list, response.data.entries);
Another problem is that controller does the job that it shouldn't, this results in design issues. $http
requests shouldn't be performed in controller. DataShareServ
service should contain methods that modify its own data.
Post a Comment for "Share Data Between Controllers Using Service Angularjs 1.6.1"