0

如何组合使用 ngressource 获得的两个对象。

每 5 秒,我调用我的服务来获取一条消息,并且我想向老年人添加一条新消息。

我的 Json 消息:

[
{"age": 0,"id": "my first tweet","name": "Hello Sarah","snippet": "It's fabulous"},
{"age": 1,"id": "my second tweet","name": "Hello dude !","snippet": "It's fabulous"}
]

我的服务:

'use strict';

/* Services */

var listlogServices = angular.module('listlogServices', ['ngResource']);

listlogServices.factory('Log', ['$resource',
  function($resource){
    return $resource('log/log1.json', {}, {
      query: {method:'GET', params:{}, isArray:true}
    });
  }]);

我的控制器和功能

'use strict';

var app = angular.module('appRecupTweetApp');


app.controller('TimerCtrl1', function TimerCtrl1($scope, Timer){

  $scope.$watch(function () { return Timer.data.myTab; },
    function (value) {
      $scope.data = value ;
      //$scope.data.push(value);
      //$scope.data = $scope.data.concat(value);
    }
  );

});

app.service('Timer', function ($timeout, Log) {

  var data = { myTab: new Array()};

  var updateTimer = function () {
    data.myTab = Log.query();
    $timeout(updateTimer, 5000);
  };

  updateTimer();

  return {
    data: data
  };
});

我尝试将我的对象与“push”和“concat”结合起来,但这是不对的。更正错误(Angular 说:$scope.data 未定义)

我可以在我的“计时器”服务或控制器中进行此操作吗?什么是好的解决方案。

在线演示:plnkr.co/edit/Vzdy9f7zUObd71Lm86Si

谢谢

纪尧姆

4

1 回答 1

0

您只需$scope.data在 TimerCtrl1 控制器中进行初始化。

 app.controller('TimerCtrl1', function TimerCtrl1($scope, Timer){
$scope.data=[];
  $scope.$watch(function () { return Timer.data.myTab; },
    function (value) {
      $scope.data = value ;
      //$scope.data.push(value);
      //$scope.data = $scope.data.concat(value);
    }
  );

});
于 2014-01-17T09:39:21.867 回答