razzamatazz
razzamatazz

Reputation: 41

Angular: Automatically update a scope reference to an object defined in a service?

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?

Upvotes: 3

Views: 216

Answers (2)

razzamatazz
razzamatazz

Reputation: 41

Two different approaches to the problem:

$broadcast

Credit goes to @doctor_Nick42 for this solution:

I add a $broadcast to the setData method of myService and catch it in parentCtrl update $scope.data accordingly.

Check the updated fiddle https://jsfiddle.net/7ehLva10/7/ for the details.

Using a function

Found a possible solution - I can define $scope.data as a function returning myService.getData(), that is

$scope.data = function() {
    return myService.getData();
};

The downside of this solution is that within the view I would need to refer to $scope.data as a function, i.e. {{data()}}.

Upvotes: 1

georgeawg
georgeawg

Reputation: 48948

Use the destination argument of angular.copy

angular.copy1

Usage

angular.copy(source, [destination]);
  • If a destination is provided, all of its elements (for arrays) or properties (for objects) are deleted and then all elements/properties from the source are copied to it.

So instead of replacing the scope reference, retain the reference, empty it, and fill it with the new contents.

function setData(newData) {
    //DO this
    angular.copy(newData, data);
    //Instead of this
    //data = newData;   
}

Upvotes: 2

Related Questions