繁体   English   中英

来自后端的JSON值的动态模型名称

[英]Dynamic model name on the JSON value from the Backend

我有一个来自后端的Json,如下所示:

var infoArray = [
        {
            "field" : "text",
            "placeholder" : "Name",
            "modelName" : "userName"
        },{
            "field" : "date",
            "placeholder" : "DOB",
            "modelName" : "userDob" 
        },{
            "field" : "text",
            "placeholder" : "Location",
            "modelName" : "userLocation"
        }
    ]; 

它已设置为最多可以有10个文本字段和4个日期字段。

由于ModelName来自后端所以我试图把它放在简单的ng-repeat中,但这似乎不起作用 这里是Plnkr Link

事实上,我自己找到了一个解决方案,代码似乎很笨重。

这是plnkr Link

还有一件事我需要考虑的是,我必须使用modelName从用户获取值,然后将其发回。

任何人都可以建议优化的解决方案或修改我的代码。 谢谢 !

你试过的几乎是正确的。 只需要删除ng-model中的花括号

 <div ng-repeat="info in infoArray">
       <input type="{{info.field}}" placeholder="{{info.placeholder}}" ng-model="info.modelName" ng-init="callFunc(info)" /> 
 </div>

演示


您可以通过以下方式执行此操作:

 var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.answers={}; $scope.infoArray = [ { "field" : "text", "placeholder" : "Name", "modelName" : "userName" },{ "field" : "date", "placeholder" : "DOB", "modelName" : "userDob" },{ "field" : "text", "placeholder" : "Location", "modelName" : "userLocation" } ]; $scope.print=function(){ console.log(answers); } }); 
 <!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> <script>document.write('<base href="' + document.location + '" />');</script> <link rel="stylesheet" href="style.css" /> <script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script> <script src="app.js"></script> </head> <body ng-controller="MainCtrl"> <div ng-repeat="info in infoArray"> <input type="{{info.field}}" placeholder="{{info.placeholder}}" ng-model="answers[info.modelName]"/> </div> <button ng-click="print()">Print</button> {{answers.userName}} {{answers.userDob}} {{answers.userLocation}} </body> </html> 

从ng-model中删除花括号,并在javascript文件中创建一个新对象,就像在我的示例中我创建了一个answers对象。 并在ng-model中使用这种方式:`

   <input type="{{info.field}}" placeholder="{{info.placeholder}}" ng-model="answers[info.modelName]"/> 

`现在,如果您想访问模型值,那么您可以这样做:

   {{answers.userName}}
   {{answers.userDob}}
   {{answers.userLocation}}

希望,这解决了你的问题。 谢谢 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM