【问题标题】:Using ng-bind-html to assign a form?使用 ng-bind-html 分配表单?
【发布时间】:2014-06-10 21:33:14
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    这不是一种非常 Angular 的方式。

    一般来说,您的控制器应该从不包含任何标记,也不应该直接与 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

    让我知道这是否满足您的需求。有很多选项可以避免在控制器中使用标记。

    【讨论】:

    • 别着急,其实用新鲜的眼光看看,我想要的是不同的路线。现在只需要弄清楚如何保持整个模板相同,除了左栏中的一个div...
    • 刚刚将我的代码从 ngRouter 移动到 ui.router;我认为解决方案是 neigh
    猜你喜欢
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    • 2013-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多