指令循环内的 2 向绑定

2-way binding inside directive loop

我正在尝试为我的客户编写一个简单的表单生成器。他们的想法是创建一个简单的表格,以后可以在不同场合使用。

为此,我正在创建一个指令,通过指令将 json 形式解析回 html。

angular
    .module('myApp')
    .directive('formbuilder', ['$timeout', '$compile', '$parse', function($timeout, $compile, $parse) {
        return {
        restrict:'AE',
        require: 'ngModel',
        scope: {
                form: '=ngModel'
            },
        link: function(scope, element, attrs) {
                $timeout(function() {
                    var bones = scope.form.structure;

                    scope.formId = scope.form.title.replace(/\W+/g, " ").replace(/\s/g,'').toLowerCase();

                    var html = '<form id="{{formId}}" class="row">';

                    angular.forEach(bones, function(bone, key) {
                        if(bone.type == 'text' || bone.type == 'checkbox') {
                            scope[key] = $parse('form.data.'+key)(scope);
                            html += '<input-field class="col s12"><input type="'+bone.type+'" id="'+bone.type+key+'" ng-model="form.data['+key+']" /> <label for="'+bone.type+key+'">'+bone.label+'</label></input-field> ';
                        }
                    })

                    html += '<p>{{form.data.input1}}</p>';

                    html += '</form>';
                    element.append($compile(html)(scope));
           })
        }
     };
}]);

问题是:我正在遍历项目以查找将它们解析回 html。这显然没有按预期工作。我可以 $parse 它,但是 2-way 绑定丢失了...

有什么想法吗?

json结构是:

$scope.form = {
        title: 'My first form',
        structure: {
            input1: {
                type: 'text',
                label: 'Input label'
            },
            input2: {
                type: 'checkbox',
                label: 'This is a checkbox'
            },
            input3: {
                type: 'checkbox',
                label: 'This is a CHECKED checkbox'
            }
        },
        data: {
            input1: 'Yannick',
            input2: false,
            input3: true
        }
    }

我会避免使用实例化 ngModelController 的 ng-model 属性。而是使用 one-time 绑定:

 <formbuilder form="::form"></formbuilder>

在指令中,使用带有 one-way (<) 绑定的隔离作用域:

.directive('formbuilder', ['$timeout', '$compile', '$parse', function($timeout, $compile, $parse) {
    return {
    restrict:'AE',
    /*
    require: 'ngModel',
    scope: {
            form: '=ngModel'
        },
    */
    scope: { form: "<" },

这会将 form 对象 reference 绑定到隔离范围。指令输入对 contents 的更改将与父作用域对象共享。不需要对对象 reference.two-way 进行绑定。

同样出于显而易见的原因,不要对 属性 访问器使用方括号表示法,而是使用点表示法:

  //html += '<input ng-model="form.data['+key+']"' 

  //USE dot notation
    html += '<input ng-model="form.data.'+key+'"'

DEMO on PLNKR.