A T
A T

Reputation: 13846

Using ng-bind-html to assign a form?

I want to click a button to replace a variable with a form. How do I do this?

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

Upvotes: 0

Views: 669

Answers (1)

Brandon Horst
Brandon Horst

Reputation: 2070

That's not a very Angular way to do it.

In general, your controllers should never contain any markup, nor should they interact directly with the DOM.

I would recommend setting a variable to determine whether or not the button has been clicked, and then using ngShow and ngHide to conditionally display the content or the form.

Here's an example:

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;
  }
});

And here's the Plunker.

Let me know if that meets your needs. There are tons of options to avoid using markup in your controllers.

Upvotes: 1

Related Questions