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 뷰를 넣을 위치를 알 수 없음)