Search code examples
javascriptangularjsangularjs-scopeangularjs-service

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?


Solution

  • 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()}}.