使用ng-bind-html分配表单?

时间:2014-06-10 21:33:14

标签: angularjs angularjs-directive html-form ng-bind-html ng-bind

我想点击一个按钮,用表格替换变量。我该怎么做?

的JavaScript

var MainCtrl = angular.module('mainCtrl', []);

MainCtrl.controller('MainCtrl', function ($scope) {
  $scope.bar = 'Foo';
  $scope.foo = function(){
    $scope.bar = '<form class="form-inline" role="form">   <div class="form-group">     <label class="sr-only" for="exampleInputEmail2">Email address</label>     <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Enter email">   </div>   <div class="form-group">     <label class="sr-only" for="exampleInputPassword2">Password</label>     <input type="password" class="form-control" id="exampleInputPassword2" placeholder="Password">   </div>   <div class="checkbox">     <label>       <input type="checkbox"> Remember me     </label>   </div>   <button type="submit" class="btn btn-default">Sign in</button> </form>';
  }
});

var fooApp = angular.module(
    'fooApp', ['ngSanitize', 'mainCtrl'];
);

HTML

  <body ng-app='fooApp' ng-controller="MainCtrl">
    <div ng-bind-html="bar"></div>
    <button class="btn" ng-click="foo()">Change bar to form</button>
  </body>

Plnkr:http://plnkr.co/edit/TQLbVWnfF9G0LVg9tiJl

1 个答案:

答案 0 :(得分:1)

这不是一种非常有角度的方法。

通常,您的控制器从不包含任何标记,也不应直接与DOM交互。

我建议设置变量以确定是否已单击该按钮,然后使用ngShow和ngHide有条件地显示内容或表单。

以下是一个例子:

HTML:

  <body ng-app='fooApp' ng-controller="MainCtrl">
    <div ng-hide="showForm">Foo</div>
    <form class="form-inline" role="form" ng-show="showForm">   <div class="form-group">     <label class="sr-only" for="exampleInputEmail2">Email address</label>     <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Enter email">   </div>   <div class="form-group">     <label class="sr-only" for="exampleInputPassword2">Password</label>     <input type="password" class="form-control" id="exampleInputPassword2" placeholder="Password">   </div>   <div class="checkbox">     <label>       <input type="checkbox"> Remember me     </label>   </div>   <button type="submit" class="btn btn-default">Sign in</button></form>

    <button class="btn" ng-click="foo()">Change bar to form</button>
  </body>

JS:

MainCtrl.controller('MainCtrl', function ($scope) {
  $scope.showForm = false;
  $scope.foo = function() {
    $scope.showForm = true;
  }
});

这是Plunker

如果符合您的需求,请告诉我。有很多选项可以避免在控制器中使用标记。