Angularjs在js中绑定动态表单构建

Angularjs bind dynamic form bulit in js

本文关键字:动态 表单 构建 绑定 js Angularjs      更新时间:2024-07-04

我有一个表单,我想在运行时通过js构建它,并在angularjs中的表单控制器中使用它
正如您在下面的示例中看到的,它没有被抛出为html,我希望它被绑定到model变量。http://jsfiddle.net/g6m09eb7/

<div>
    <form ng-controller="TodoCtrl" ng-submit="blabla()">
        <div ng-repeat="field in fields">{{field.input}}</div>
    </form>
</div>
function TodoCtrl($scope) {
    $scope.model = {
        'FirstName': 'Test',
        'LastName': 'Test Last'
    }
    $scope.fields = [{
        input: '<input type="text" ng-model="model.FirstName">'
    }, {
        input: '<input type="text" ng-model="model.LastName">'
    }, ];
}

首先,我将向您展示如何在您尝试完成它时使其发挥作用,以便提供信息。这不是你应该用来解决整体问题的方法。本例将获取文档中的html,但不会使用Angular进行编译。要做到这一点,您必须有一个不同的指令,像这样(单击)。这是一种糟糕的做法。

angular.module('myApp', [])
.controller('TodoCtrl', function($scope) {
    $scope.fields = [{
        input: '<input type="text" ng-model="model.FirstName">'
    }, {
        input: '<input type="text" ng-model="model.LastName">'
    }, ];
})
// filter to make Angular trust the html
.filter('safeHtml', ['$sce', function ($sce) { 
    return function (text) {
        return $sce.trustAsHtml(text);
    };    
}])
;                     
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app="myApp" ng-controller="TodoCtrl">
   <!-- use ng-bind-html on trusted html to bind it (see the js) -->
  <div ng-repeat="field in fields" ng-bind-html="field.input | safeHtml"></div>
</form>

相反,你可以很自然地做到这一点。只需使用对象的属性作为ng-repeat的条件。简单干净!

angular.module('myApp', [])
.controller('TodoCtrl', function($scope) {
  $scope.model = {
    'FirstName': 'Test',
    'LastName': 'Test Last'
  };
})
;                     
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app="myApp" ng-controller="TodoCtrl">
  <div ng-repeat="(key,value) in model">
      <input type="text" ng-model="model[key]"/>
  </div>
</form>

请确保避免将控制器与DOM操作联系起来。如果您在控制器中有html片段,那么您的方法可能偏离了轨道。DOM操作应该完全通过指令来完成。