如何删除angularjs中请求对象中的字段

时间:2014-12-24 09:46:01

标签: javascript angularjs

我从angularjs控制器向服务器发出请求以获取对象,我希望在视图显示之前删除对象中的字段。 Folloiwng是我的代码

$scope.findOne = function() {
    $scope.order = Orders.get({
        orderId: $stateParams.orderId
    });
    delete $scope.order._id;
    console.log(JSON.stringify($scope.order));
};

打印

{"$promise":{},"$resolved":false}

它不会删除id字段。我的视图显示了我的对象_id。如何删除该字段?

以下是我的服务档案

'use strict';

//Orders service used for communicating with the orders REST endpoints
angular.module('orders').factory('Orders', ['$resource',
    function($resource) {
        return $resource('orders/:orderId', {
            orderId: '@_id'
        }, {
            update: {
                method: 'PUT'
            }
        });
    }
]);

当我将findOne()更改为

$scope.findOne = function() {
    Orders.get({
        orderId: $stateParams.orderId
        }).success(function(res)//(this is line number 56)
        {
            delete res.data._id;
            $scope.order = res.data;
    });
};

我在控制台

中收到此错误
 TypeError: undefined is not a function
    at Scope.$scope.findOne (http://localhost:3000/modules/orders/controllers/orders.client.controller.js:56:14)
    at http://localhost:3000/lib/angular/angular.js:10903:21
    at Scope.$eval (http://localhost:3000/lib/angular/angular.js:12811:28)
    at pre (http://localhost:3000/lib/angular/angular.js:20125:15)
    at nodeLinkFn (http://localhost:3000/lib/angular/angular.js:6732:13)
    at compositeLinkFn (http://localhost:3000/lib/angular/angular.js:6146:13)
    at publicLinkFn (http://localhost:3000/lib/angular/angular.js:6042:30)
    at http://localhost:3000/lib/angular-ui-router/release/angular-ui-router.js:3905:9
    at nodeLinkFn (http://localhost:3000/lib/angular/angular.js:6752:13)
    at compositeLinkFn (http://localhost:3000/lib/angular/angular.js:6146:13) <section data-ng-controller="OrdersController" data-ng-init="findOne()" class="ng-scope">angular.js:10126 (anonymous function)

3 个答案:

答案 0 :(得分:1)

Orders.get函数返回一个promise,请记住你的代码应该是这样的:

Orders.get({orderId: $stateParams.orderId}).then(function(order) {
  delete order._id;
  $scope.order = order;
});

希望这有帮助, 让我知道。

干杯!

答案 1 :(得分:1)

默认情况下,

get返回一个promise对象。这样做的方法是

$scope.findOne = function() {
    Orders.get({
        orderId: $stateParams.orderId
        }).success(function(res)
        {
            delete res.data._id;
            $scope.order = res.data;
    });
};

答案 2 :(得分:1)

我将功能更改为

    $scope.findOne = function() {
        var order = Orders.get({
            orderId: $stateParams.orderId
        }, function()
        {
            order.order_type = 'new';
        });
         $scope.order = order;
    };

它有效。我想知道angularjs update中的语法是否有所改变。 https://docs.angularjs.org/api/ngResource/service/ $ resource中提到了类似的语法。虽然我无法弄清楚成功回调的其他答案不起作用的原因。