Jacob Stamm Jacob Stamm - 6 months ago 41
AngularJS Question

How can I conditionally display HTML in a button using AngularJS?

I would like for a certain button element to contain plain text by default, but then contain HTML based on some variable in my Angular scope. My goal is to have the button say "Save", but then become disabled and display a loading wheel when clicked (while awaiting a response from a long AJAX request). The problem is, Angular is displaying the literal text of my ternary operator in the button rather than the result of the expression.

Here's what my button looks like:

<button type="submit" ng-disabled="IsLoading" ng-click="OnClick()">
{{ IsLoading === false ? "Save" : "<i class='fa fa-spinner fa-pulse'></i>" }}
</button>


Broken Angular code in button

When I change the HTML to just some plain text (for instance, "Loading..."), then it works fine.

How can I get it to display the result of the expression rather than the text of the expression itself? Thanks.

Side note: I tried to get a demo up and running, but it seems that I can't figure out how to wire up the Angular properly using JSFiddle. This is not the purpose of my question, but I'd really like to know where I'm going wrong so I can successfully make simple Angular demos in the future. Any advice is appreciated.

Answer

Check out this fiddle

<div ng-app="myApp" ng-controller="LoadingController">
  <div style="float: left;">
    <button type="submit" ng-disabled="IsLoading" ng-click="OnClick()">
      <span ng-if="!IsLoading">
        Save
      </span>
      <span ng-if="IsLoading">
        <i class="fa fa-spinner fa-pulse"></i>
      </span>

    </button>
  </div>
  <div style="float: left;">
    <button type="submit" ng-disabled="IsLoading" ng-click="OnClick()">
     <span ng-if="!IsLoading">
        Save
      </span>
      <span ng-if="IsLoading">
        Loading...
      </span>
    </button> 
  </div>
</div>

js

angular.module("myApp",[]).controller('LoadingController', function   LoadingController ($scope,$sce) {
    $scope.IsLoading = false;

  $scope.OnClick = function() {
    $scope.IsLoading = true;
    window.setTimeout(function() {
        $scope.IsLoading = false;
    }, 1000);
  };
});

note:Angular 1.1.5 added a ternary operator support, and your fiddle pointing to older version, that's why its not working