2016-03-15 94 views
1

我有一个基于所传入的数据生成表单项目绑定嵌套对象

我们支持可能字段类型,但是,例如,这里是input模板:

<label> 
    {{fieldSchema.label}} 
    <input type="{{fieldSchema.attributes.type}}" 
      name="{{fieldSchema.attributes.name}}" 
      ng-model="model[ fieldSchema.attributes.name ]" /> 
</label> 

这对于平板机型的伟大工程,但如果模型嵌套,它分崩离析,如:

$scope.model = { 
    manager: { 
     first_name: 'John' 
    } 
} 
$scope.fieldSchema.attributes.name = 'manager.first_name'; 

是否有使用方式$parse$interpolate或类似的ng-model?我见过如何在这个结构中获取数据的示例,但我一直无法找到双向绑定解决方案。

(注:采用了棱角分明的版本1.5.0)

编辑:这里是一个普拉克,希望这使得它更加清晰。 http://plnkr.co/edit/4E8jlsnuy5HkCZPxSf5z?p=preview

+0

我可以知道你的输入模板是如何渲染的吗? –

+0

我正在抓取一个HTML模板(基于'fieldSchema'中的内容),并使用'element.html(html);' –

+0

根本不清楚具体问题是什么。演示会帮助 – charlietfl

回答

0

我最终做了Amit在评论中提出的建议。谢谢,阿米特!

首先,我在指令创建一个getter/setter函数:

function getterSetter(newValue) { 

    var getter = $parse('model.' + $scope.wxFormField.attributes.name), 
     setter = getter.assign; 

    return arguments.length ? setter($scope, newValue) : getter($scope); 
} 

然后,我改变了ng-model到该功能,并添加了ng-model-options指令。

<label> 
    {{fieldSchema.label}} 
    <input type="{{fieldSchema.attributes.type}}" 
      name="{{fieldSchema.attributes.name}}" 
      ng-model="formFieldFunctions.getterSetter" 
      ng-model-options="{ getterSetter: true }" /> 
</label> 
1

如果模板输入模板html可以通过代码控制,那么在呈现/附加HTML到DOM之前,请按照以下方式进行操作。

ng-model="model[fieldSchema.attributes.name]" 

ng-model="model['manager']['first_name']" 

代码

function createNgModel(model){ 
    var values = model.split('.') 
    //and then create a format it do have below format 
    //model['manager']['first_name'] 
}; 

var template = '<label>'+ 
    '{{fieldSchema.label}}'+ 
    '<input type="{{fieldSchema.attributes.type}}"'+ 
      'name="{{fieldSchema.attributes.name}}"'+ 
      'ng-model="+ createNgModel(fieldSchema.attributes.name) +" />'+ 
'</label>'; 

或者说一个很好的选择将只是通过附加返回fieldSchema.attributes.name字符串值由@Amit的意见建议

var template = '<label>'+ 
    '{{fieldSchema.label}}'+ 
    '<input type="{{fieldSchema.attributes.type}}"'+ 
      'name="{{fieldSchema.attributes.name}}"'+ 
      'ng-model="model.'+ fieldSchema.attributes.name+'" />'+ 
'</label>'; 
+0

这适用于一个领域,但我有几十个,在'ng-repeat'中,并不是所有的都在'manager'字段下。 –

+0

哦,我明白你在说什么......我宁愿不把所有的模板都移到指令中,但我想这是一个选项。 –

+0

@MattGrande查看更新后的答案...按照Amit的评论 –