好吧,我对整个AngularJS事情都不熟悉,我可能会比我的手更脏,但这就是我要做的事情:
这是我到目前为止所拥有的:
循环HTML
<div ng-repeat="info in customerCtrl.personalInfoFields">
<edit-field info="info" model="customerCtrl.customer"></edit-field>
</div>
剥离控制器:
customerCtrl.personalInfoFields = [{'field':'NAME', 'type':'text'},
{'field':'SURNAME', 'type':'text'},
{'field':'MAIL', 'type':'email'}]
customerCtrl.customer = customersFactory.customerDetails; // filled through a Factory, works fine if I just draw every single field manually in the HTML
指令:
myApp.directive('editField', ['$http', '$compile', 'capitalizeFilter', function($http, $compile, $capitalizeFilter) {
return {
scope: {
info: "=",
model: "="
},
replace: true,
template: '<div ng-include="url"></div>',
link: function(scope, element, attrs){
scope.url = '/views/fields/edit'+$capitalizeFilter(scope.info.type)+'.html';
}
/*templateUrl: function(elem,attrs)
{
if(typeof attrs.info.type === "undefined")
return '/views/fields/editText.html';
return '/views/fields/edit'+attrs.info.type+'.html'
},*/
};
}]);
editText.html(其他文件现在差别不大,稍后会做)
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-4">
<div class="form-group">
<label class="control-label">{{'customers.'+info.field | i18n | capitalize}}</label>
<input type="text" class="form-control" ng-model="model[info.field]"/>
</div>
</div>
现在,在字段内我只得到[object Object],如果我将实际字段本身作为模型而不是整个客户对象传递它显示正常但它没有绑定(我可以更改字段内容但它不会反映在控制器对象中) 注释的templateUrl部分不起作用,因为AngularJS只为整个ng-repeat函数编译一次URL,所以我坚持使用未定义的变量 - &gt;每个人的editText
如何在为每种字段类型抓取正确的模板的同时成功绑定字段?
答案 0 :(得分:1)
问题解决了,显然是在调用
$compile(element.contents())(scope);
修复了绑定,但我仍然必须将整个customer对象传递给指令然后使用
ng-model="model[info.field]"
获得所需的结果