使用字符串键绑定嵌套对象

时间:2016-03-15 15:47:40

标签: javascript angularjs

我有一个项目,可以根据传入的数据生成表单。

我们支持may字段类型,但是,例如,这里是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内使用$interpolateng-model或类似内容?我已经看到了如何在此结构中获取数据的示例,但我无法找到双向绑定解决方案。

(注意:使用角度版本1.5.0)

编辑:这是一个插件,希望这让它更清晰。 http://plnkr.co/edit/4E8jlsnuy5HkCZPxSf5z?p=preview

2 个答案:

答案 0 :(得分: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中添加{@ 1}}返回的字符串值,如@Amit在评论中所建议的那样

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

答案 1 :(得分: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>
相关问题