【问题标题】:How to update item from $scope ng-repeat after saving using $resource使用 $resource 保存后如何从 $scope ng-repeat 更新项目
【发布时间】:2013-03-31 18:31:13
【问题描述】:

我有一个显示项目列表的角度视图,每个项目都有两个按钮可将每个广告系列设置为暂停/开始。我知道这是 angular $resource 的一个非常基本的问题,但我无法在成功 $start 时更新项目(在成功回调中我无法访问与该项目相关的任何内容)。

function CampaignsListCtrl($scope, Campaign, $resource) {
    $scope.campaigns = Campaign.query();

    $scope.startCampaign = function () {
        var c = new Campaign(this.campaign);
        c.status = 1;
        c.$start(function success(response) {
               //here I'd like to update the value but can't access the item.
               //for example this.campaign.status = 1 doesn't work
               //how can I access the ng-repeat item to update it on success $start?
               //the response represents the updated Object

               console.log (response);

        }, function error (response) {
           console.log (response)
        });
    }

    $scope.pauseCampaign = function () {
        var c = new Campaign(this.campaign);
        c.status = 0;
        c.$pause(function success(response) {
               console.log (response);

        }, function error (response) {
           console.log (response)
        });
    }

}
//// and Campaign is defined as factory
mongoAPI.
factory('Campaign', ['$resource', '$http', function($resource, $http) {
        var actions = {
            'start': {method:'POST'},                           
            'pause': {method:'POST'}                 
        }
        var res = $resource('/api/campaign.js',{}, actions)
        return res;
}]);

在我的观点中:

<div ng-repeat="campaign in campaigns">
     <button type="button" ng-show="campaign.status==0" ng-click="startCampaign(campaign)" class="btn"><i class="icon-play"></i></button>
     <button type="button" ng-show="campaign.status==1" ng-click="pauseCampaign(campaign)" class="btn"><i class="icon-pause"></i></button>
</div>

【问题讨论】:

    标签: angularjs angularjs-ng-repeat angularjs-service angular-resource


    【解决方案1】:

    这是一个与闭包/范围相关的问题,而不是 Angular 本身。在成功处理程序中,this 不再是作用域,因此无法访问this.campaign。您实际上可以通过多种方式解决此问题。

    我相信,最简单的方法是接收 campaign 作为参数并从那里引用它:

    你的 HTML 中已经有了这个:

    ng-click="startCampaign(campaign)"
    

    所以接收并使用它:

    $scope.startCampaign = function (campaign) {
        var c = new Campaign(campaign);
        c.$start(function success(response) {
          campaign.status = 1;
        },
        ...
    };
    

    【讨论】:

      猜你喜欢
      • 2013-06-25
      • 1970-01-01
      • 2016-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多