1

I am learning AngularJS. I have an app with a controller that looks like the following:

function myController($scope) {
  $scope.isOn = false;
  $scope.flip = function() {
    $scope.isOn = !$scope.isOn;
  }
}

My view has the following code:

<div ng-controller="myController">
  <button ng-click="flip()">{{isOn}}</button>
</div>

I want isOn to be a true/false value in my controller. However, in my view I want to show "On" if the flag is true. If the flag is false, I want to show "Off". How do I do that? I thought I could possibly use a filter. However, I didn't have any luck with that approach.

4 Answers 4

2

Use poor mans ternary operator:

<div ng-controller = "fessCntrl"> 
  <button ng-click="flip()">{{(isOn) && 'On' || 'Off'}}</button>
</div>

Demo 1 Fiddle

or (from angularjs > 1.1.5)

<div ng-controller="ctrlRead"> 
  <button ng-click="flip()">{{isOn ? 'On' : 'Off'}}</button>
</div>  

Demo 2 Fiddle

Sign up to request clarification or add additional context in comments.

Comments

1

Another alternative would be to do the logic in the controller

html template:

<div ng-controller="myController">
    <button ng-click="flip()">{{isOnLabel}}</button>
</div>

controller:

function myController($scope) {
    var isOn = false;
    $scope.isOnLabel= 'Off';
    $scope.flip = function() {
        isOn = !isOn;
        $scope.isOnLabel = isOn?'On':'Off';
    };
};

If you need isOn to be on the $scope then in the controller change isOn with $scope.isOn

function myController($scope) {
    $scope.isOn = false;
    $scope.isOnLabel= 'Off';
    $scope.flip = function() {
        $scope.isOn = !$scope.isOn;
        $scope.isOnLabel = $scope.isOn?'On':'Off';
    };
};

jsFiddle demo

Comments

0

You can use the ?: operator

<div ng-controller="myController">
  <button ng-click="flip()">{{isOn?"On":"Off"}}</button>
</div>

Just verify your version of Anugular supports it.

Comments

0

You can also go with a filter (though probably it's not worth it). That way you would have something like:

<div ng-controller="myController">
    <button ng-click="flip()">{{isOn | toggleFilter}}</button>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.