2

当我收到来自服务器的响应时,我试图弄清楚如何使用服务更新我的模型。

我的 JSON 结构:

var dgs = [{id    :1,
            driver:'Sam',
            type:  'bus',
            segments:[ {id:1,origin:'the bakery',arrival:'the store'},
                     {id:2,origin:'the store' ,arrival:'somewhere'}]
            },
            { ... },
            { ... }
          ];

索引.html:

<body ng-controller="dgCtrl">
  <div ng-repeat="dg in dgs" drivegroup></div>
</body>

dg.html:

<div> {{ dg.driver }} </div>
<div> {{ dg.type }} </div>
<div ng-repeat="seg in dg.segments" segments></div>

段.html:

<div>
  <input ng-model="seg.origin" ng-blur="updateSegment()"/></div>
<div>
  <input ng-model="seg.arrival" ng-blur="updateSegment()"/></div>

我的控制器如下:

function dgCtrl($scope,$http,DriveGroup,Segment) {
  var segment =  new Segment;
  $scope.dgs = DriveGroup.query();  // load & display all drive groups

  $scope.updateSegment = function() {
    var seg = this.seg;
    segment.seg = this.seg;
    segment.id = this.seg.id;
    segment.$update(function(data,x) {
      // seg.origin = data.origin - This updates the origin.
      seg = data; // This doesn't work. How can I do this?
  });
}

我的服务:

angular.module('dgService',['ngResource']).
  factory("DriveGroup",function($resource) {
    return $resource(
      '/path/dgs',
      {},
      {update:{method:'PUT'}}
    );
});

angular.module('Segment',['ngResource']).
  factory('Segment',function($resource) {
    return $resource(
      '/path/seg/:id',
      {id:'@id'},
      {update:{method:'PUT'}}
    );
});

我的问题是我不确定如何使用$resource. 我想对某个细分市场进行更改,所以我提出了一个put请求。我从服务器得到响应并想更新我的模型(这不起作用)。

我是 Angular 的新手,所以如果您发现任何其他明显的错误/或结构问题,我们将不胜感激。谢谢。

编辑

以下实现了我想要的结果,但这是否正确?

$scope.updateSegment = function() {
  var seg = this.seg,
      segment = new Segment(seg);

  segment.$update(function(data,x) {
    angular.extend(seg,data);
  });
}
4

0 回答 0