AngularJS ng-model form driven by ng-repeat over UI model description data how to?

烂漫一生 提交于 2019-12-29 09:26:12

问题


The JSFiddle http://jsfiddle.net/vorburger/hyCTA/3/ illustrates a (working) "UI modeling" idea I had with AngularJS; note the form is not actually coded out in the HTML template, it's driven by uimodel JSON (which in turn describes how the datamodel is to be rendered/edited):

<div ng-repeat="auimodel in uimodel">
    <label>{{$index + 1}}. {{auimodel.label}}</label>
    <input ng-model="datamodel[auimodel.model]" type="{{auimodel.type}}" />
</div>

Trouble is, as soon as my 'model' isn't a simple property, but a 'path', then my square bracket dynamic keys 'trick' doesn't work anymore of course.. as illustrated by the (broken) http://jsfiddle.net/vorburger/8CxRC/1/ JSFiddle. Any suggestions how one could do this?

PS: Or would something like this necessarily need a complete custom directive rather sooner than later? I’d rather not have to do this, if that’s possible at all, in order to keep creation & maintenance of such UI model “meta templates” as simple as possible...


回答1:


I've just figured out one (but may be not the best?) way to achieve this myself.. see http://jsfiddle.net/vorburger/8CxRC/3/ - basically still based on my square bracket dynamic keys 'trick', but with some pre-processing:

   for (var i = 0; i < $scope.uimodel.length; i++) {
        var resolvedModelProperty = $scope.datamodel;
        var remainingPath = $scope.uimodel[i].model;
        while (remainingPath.indexOf('.') > -1) {
            var nextPathSlice = remainingPath.substr(0, remainingPath.indexOf('.'));
            resolvedModelProperty = resolvedModelProperty[nextPathSlice];
            remainingPath = remainingPath.substr(remainingPath.indexOf('.') + 1);
        }
        $scope.uimodel[i].modelB = resolvedModelProperty;
        $scope.uimodel[i].modelL = remainingPath;
    }



回答2:


You are along the same lines as my own project Metawidget. Metawidget's equivalent to what you are after is covered by metawidget.angular.widgetprocessor.AngularWidgetProcessor:

https://github.com/metawidget/metawidget/blob/master/modules/js/angularjs/src/main/webapp/lib/metawidget/angular/metawidget-angular.js

Although I didn't find the need to use the square bracket notation (I just did foo.bar.baz). Also the magic line:

$compile( widget )( scope.$parent );

Which turns the raw HTML you instantiate dynamically into fully-functioning Angular code.

If you get chance to take a look at Metawidget, I'd appreciate your feedback! Tutorial starts here.



来源:https://stackoverflow.com/questions/17841915/angularjs-ng-model-form-driven-by-ng-repeat-over-ui-model-description-data-how-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!