AngularJS:如何观看服务对象

时间:2015-05-20 14:08:06

标签: javascript arrays angularjs kendo-ui

我尝试过使用手表功能的不同示例,但我无法使其正常工作。我正在观看一个包含对象数组的服务,每个对象包含一个数组数组。我需要观察数组的变化。

JSON

 [{
    "name": "Chantal Hamlet - Green Castle Homes",
    "subId": "10223",
    "bldId": "13551",
    "data": [
        [179900, 1386],
        [214900, 1440],
        [194500, 1496],
        [217900, 1504],
        [189900, 1542],
        [184900, 1546],
        [192500, 1570],
        [189900, 1576],
        [191900, 1598],
        [204900, 1626],
        [219900, 1651],
        [212900, 1704],
        [214900, 1787],
        [219900, 1837],
        [224900, 1857]
    ]
 }, {
     "name": "Ella Sea Condos - Sahnow Construction",
     "subId": "9761",
     "bldId": "27380",
     "data": [
         [199900, 1500]
     ]
 }]

观看功能

$scope.$watchCollection(function () {
    return chartService.series
},
function (rawData) {
    $scope.seriesData = rawData;
});

服务

chart.factory('chartService', function () {
return {
    getSeries: function () {
       return this.series;
    },
    setSeries: function (series) {
        this.series = series;
    },

1 个答案:

答案 0 :(得分:1)

问题是你的setSeries函数正在改变被监视的对象。

想想它

chartService.series = ObjectA

观看ObjectA

chartService.series = ObjectB

ObjectA没有改变。

要解决此问题,您需要将其包装在一个不会更改的较大对象中。



angular.module('chartModule', [])
.controller("chartController", ['$scope', 'chartService',
  function($scope, chartService) {
    $scope.seriesData = chartService.seriesContainer;


    $scope.changeData = function() {
      chartService.seriesContainer.series = [{
        "name": "New Name",
      }];
    }
  }
]).factory('chartService', function() {
  return {
    getSeries: function() {
      return this.series;
    },
    setSeries: function(series) {
      this.series = series;
    },
    seriesContainer: {
      series: [{
        "name": "Chantal Hamlet - Green Castle Homes",
      }]
    }
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="chartModule">
  <div ng-controller="chartController">
    {{seriesData.series[0].name}}
    <button ng-click="changeData()">Change Data</button>
  </div>
</body>
&#13;
&#13;
&#13;

如果您使用包装纸,您实际上甚至不需要手表,它会自动发生