我正在尝试构建一个复杂的帖子请求,以便在我的Angular应用中运行报告。
我有一个输入列表,所有输入都是通过ng-repeat
动态生成的,我的html的简单版本就像这样。
<div ng-repeat="filter in lists.filters">
<input type="checkbox" ng-model="report.options.filters[filter.value]['type']/>
<input type="text" ng-model="report.options.filters[filter.value]['values']/>
</div>
ng-repeat
循环遍历此数组
[
{name: 'Advertisers', value: 'advertisers'},
{name: 'Sizes', value: 'sizes'},
{name: 'Campaign IDs', value: 'campaigns'},
{name: 'Creative IDs', value: 'creatives'},
{name: 'Publishers', value: 'publishers'},
{name: 'Placement IDs', value: 'placements'},
{name: 'Seller Types', value: 'seller_types'},
{name: 'Impression Types', value: 'impression_types'},
{name: 'Bid Types', value: 'bid_types'},
{name: 'Seller Members', value: 'seller_members'},
{name: 'Buyer Members', value: 'buyer_members'},
{name: 'Insertion Order Ids', value: 'insertion_orders'},
{name: 'Countries', value: 'countries'},
{name: 'Site Ids', value: 'sites'},
{name: 'Sources', value: 'sources'}
];
我发回的JSON需要像这样结构化:
"filters": {
"state": "all",
"campaigns": {type:"include", values":[1,2]},
"creatives": {type:"exclude","values":[1,2]},
"publishers": {"values":[1,2]},
"placements": {type:"exclude",values":[1,2]},
"advertisers": {"values":[1,2]},
"sizes": {"values":[1,2]},
"countries": {"values":[1,2]},
"insertion_orders": {"values":[1,2]},
"sites": {"values":[1,2]},
"bid_types": {"values":[1,2]},
"seller_types": {"values":[1,2]},
"impression_types": {"values":[1,2]},
"seller_members": {"values":[1,2]},
"buyer_members": {"values":[1,2]},
"sources": {"values":[1,2]}
}
当我这样做时,Angular会抛出错误:'Cannot set property 'values' of undefined'
和'Cannot set property 'type' of undefined'
然而,如果我这样做(在ng-repeat内)
<input type="text" ng-model="report.options.filters[filter.value]/>
或者在ng-repeat之外
<input type="text" ng-model="report.options.filters[filter.value]['values']/>
不会抛出任何错误,一切正常。我很肯定filter.value是在范围内定义并且可用的,即使Angular认为它不是出于某些原因。
我不太确定我做错了什么。任何帮助深表感谢。
答案 0 :(得分:0)
Angular似乎认为report.options.filters[filter.value]
未定义。
你可以初始化它。可以在控制器中使用ngInit
:
<div ng-repeat="filter in lists.filters"
ng-init="report.options.filters[filter.value]=
report.options.filters[filter.value]||{}">
<input type="checkbox" ng-model="report.options.filters[filter.value]['type']" />
<input type="text" ng-model="report.options.filters[filter.value]['values']" />
</div>
另请参阅此 short demo 。
<子>
上面的代码假定$scope.report.options.filters
已初始化
如果没有,您也应该初始化它。
子>