2016-06-09 47 views
0

我试图解决在AngularJS中我的模型,视图和指令的设计问题。基本上,我有一个按类别在页面上填充产品的清单,每个清单都添加了数量字段。我需要这些数量字段与我从服务器返回并发布到服务器的orderItem数组进行双向绑定。匹配两个模型与指令

当我更改产品的数量字段时,可以使用新的orderItem更新oc.order.orderItems数组。但是,当我尝试填充先前的订单时,我在更新模型和视图时遇到问题。我的问题的大部分源于我应该如何处理与我的指令相关的数量字段的ngModel属性。

这里是我的一些代码示例(稍微剥离下来)。如果有什么需要澄清,以帮助协助,因为我知道这听起来很混乱,请让我知道。

产品型号:

var product = { id: 1, category_id: 1, name: 'Apple' }; 

OrderItem的型号:

var orderItem = { id: 1, order_id: 1, product_id: 1, quantity: 2 }; 

查看:

<div ng-repeat="category in oc.categories"> 
    <h2>{{ category.name }}<h2> 
    <div ng-repeat="product in category.products"> 
     <h3>{{ product.name }}</h3> 

     <input type="number" placeholder="Quantity" 
       order-item="product" ng-model="oc.order.orderItems[$index]" /> 
    </div> 
</div> 

指令:

angular 
    .module('OrderApp') 
    .directive('orderItem', function ($window) { 
     return { 
      restrict: 'A', 
      scope : { 
       product: '=orderItem' 
      }, 
      require: 'ngModel', 
      link: function (scope, element, attrs, ngModelCtrl) { 

       ngModelCtrl.$parsers.push(function (viewValue) { 
        if (!viewValue > 0) return; 

        if (!scope.id) scope.id = 0; 
        if (!scope.order_id) scope.order_id = 0; 

        return { 
         id: scope.id, 
         order_id: scope.order_id, 
         quantity: viewValue, 
         product_id: scope.product.id 
        }; 
       }); 

       ngModelCtrl.$formatters.push(function (modelValue) { 
        if (!modelValue) return; 

        if (!modelValue.id) scope.id = modelValue.id; 
        if (!modelValue.order_id) scope.order_id = modelValue.order_id; 

        return modelValue.quantity; 
       }); 

      } 
     }; 
    }); 

(指令看起来并不正确,不知道在哪里放置$ render和scope $ watch)

回答

0

以不同的方式查看问题后,我发现我的解决方案不应该是指令,但实际上是用于在控制器之间共享每个模型的数据的服务。

解决方案:Gist