标签云

微信群

扫码加入我们

WeChat QR Code

I have an angular app myAppwith a service myService, holding an object datathat is used by two Controllers, parentCtrl and childCtrl the latter inheriting from the former: https://jsfiddle.net/OleWahn/7ehLva10/2/I reference data within parentCtrl by $scope.data = myService.getData() which also makes it accessible from childCtrl.I define data in the closure of myService, hence $scope.data is just a reference to data.Thus, I can alter data's properties within the child controller and everyone, myService, parentCrl and childCtrl will be aware of these changes. So far, so good.My problem here is the following: If I want to overwrite the entire data object I invoke myServices method setData within childCtrl.Again, I'd like everyone to be notified that data has changed. $scope.data however still points to the initially defined object and will not be notified by myService that data has changed, which will stand as my final question: Is there a way to automatically update a scope reference to an object defined in a service?


This is even better than I thought it would be, thanks a lot!

2019年05月24日09分19秒

It doesn't answer my original question though, I guess I did not really put itvery well. what if I want to change the references instead of exchanging the object's contents? Say for instance, I have an array containing several data-like objects and I want $scope.data to point atany of them. Now in childCtrl I'd like to alter that pointer via the setter of myService - how can I make $scope.data aware of that change?

2019年05月24日09分19秒

I edited the fiddle accordingly jsfiddle.net/OleWahn/7ehLva10/5

2019年05月24日09分19秒

razzamatazz I'm not sure, if this is what you need, but maybe you should look at $broadcast. With this function you can 'notify' controllers about your data changes from the service. I know that overusing of $broadcast isn't a good practice, but maybe it could help you.

2019年05月24日09分19秒

doctor_Nick42 thanks, this is exactly what I'm looking for! I'd edit my answer below to collect all solutions for the problem, but the credit for this goes to you

2019年05月24日09分19秒