在控制器中保存错误的数据(AngularJS)

时间:2016-02-26 00:28:26

标签: angularjs

我有两个控制器OrderMeal。当我选择2份相同的饭菜时,这段代码出错:

$scope.meal is undefined

我该怎么办?

    angular.module('mocs')
    .controller('ordersCtrl', [
        '$scope',
        'orders',
        'meals',
        'myService',
        function($scope, orders, meals, myService){
            $scope.orders = orders.orders;
            $scope.meal = myService.getOrder();

            if (!angular.isUndefined($scope.meal)) {
                orders.create({
                    meal_id: parseInt($scope.meal.id),
                    status: "ordered",
                });
            }
                                   ...

即使存在错误,我的错误餐也会保存到订单中。

我的服务代码:

.factory('myService', function() {
    var mealToOrder = {};

    return {
        setOrder: function(meal) {
          return mealToOrder.meal = meal;
        },
        getOrder: function() {
        return mealToOrder.meal;
        }
    };
});

我的工厂:

angular.module('mocs')
.factory('orders', [ '$http',function($http){
     ...
 o.create = function(order) {
      return $http.post('/orders.json', order)
      .success(function(data){
        o.orders.push(data);
        order = '';
      });
    };

return o;
}]);

0 个答案:

没有答案