Angularjs绑定了js中构建的动态表单

时间:2015-03-01 05:24:30

标签: javascript angularjs forms binding

我有一个表单,我想在运行时通过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">'
    }, ];
}

1 个答案:

答案 0 :(得分:3)

首先,为了提供信息,我将向您展示如何完成这项工作。这不是您应该用来解决整体问题的方法。此示例将获取文档中的html,但不会使用Angular进行编译。为此,您必须使用其他指令 like this (click) 。这是一种糟糕的做法。

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操作应该完全使用指令完成。