Tester
Tester

Reputation: 808

AngularJS update shared data in a Service from $http

Please see this Plunker. I have a myApp.common.sharedata module to share data between two modules myApp.interactive.layout.menu and myApp.interactive.layout.chart.

If you click the checkbox in the menu module, it will call service sharedata.check(key); to update the shared data.

In common/sharedata/sharedata.service.js function sharedata.check. I use sharedata.series = response.data.data; to update the data from $http, it is not working. The data is not synchronized to module myApp.interactive.layout.menu and myApp.interactive.layout.chart. I also tried sharedata.series = angular.copy(response.data.data);, it is not working too. I have to do

for(var i=0; i<response.data.data.length;i++){
    sharedata.series[i] = response.data.data[i];
}

Any suggestions? My ultimate goal is to use $http to initialize the shared data in module myApp.common.sharedata. Now I'm using the static code. If I use

$http.get("https://reqres.in/api/users")
  .then(function(response) {
  sharedata.series = (response.data.data);
});

The data does not synchronized to module myApp.interactive.layout.menu and myApp.interactive.layout.chart too.

Upvotes: 1

Views: 65

Answers (1)

PSK
PSK

Reputation: 17943

There is a small issue which you need to fix.

Change your InteractiveChartCtrl as following.

'use strict';

angular.module('myApp.interactive.layout.chart', ['myApp.common.sharedata'])

.controller('InteractiveChartCtrl', ['$scope', 'sharedata',function($scope,sharedata) {

        $scope.menuSeries = sharedata; //MODIFIED HERE

        $scope.$watch('menuSeries', function(newValue, oldValue) {
            console.log('menuSeries changed');
            console.log(newValue);
        },true);

}]);

I have changed $scope.menuSeries = sharedata; //MODIFIED HERE

And your chart.html as following.

<div>
    <div>
            <ul>
                    <li ng-repeat="item in menuSeries.series" class="list-group-item">
                        <label class="interactive_chart_metrics">
                            <input type="checkbox" class="metrics" id="{{item.id}}" ng-click="seriesMenuClick($event,checkStatus)" ng-model='checkStatus' ng-checked ="item.selected" alt="{{item.first_name}}">&nbsp;{{item.first_name}}</label>
                    </li>
                </ul>
        </div>
    <div>
        {{menuSeries}}
    </div>

</div>

I have changed here <li ng-repeat="item in menuSeries.series" class="list-group-item">

This will fix the issue. Check the plnkr.

Updated for Menu

Upvotes: 1

Related Questions