0

Below you can see an example of my Code - The app is running fine, so when I click on 'Toggle', the app is switching between the two Variables.

<body>
<div ng-init="value = 'off'" ng-app='app' ng-controller="myctrl">
<h1 ng-click="value = { 'on': 'off', 'off':'on'}[value]; event.PreventDefault;">Toggle</h1>
  <h3 ng-show="value == 'on'" >{{var1}}</h1>
  <h3 ng-show="value == 'off'" >{{var2}}</h1>  
</div>

<script>
(function () {
'use strict';

angular.module('app', [])
.controller('myctrl', myctrl);

function myctrl($scope){
  $scope.var1 = "Its on";
  $scope.var2 = "Its off";
}
})();
</script>

Following Question: How can I implement this, or what is best practice that I just need one "h3" tag to switch between the variables ? Because I have a lot of other information in my html tag and I always repeating me for just toggle of two Variables...

3 Answers 3

3

You can add the condition direcly in the curly brackets

<h3>{{value == 'on' ? var1 : var2}}</h3>

Demo: https://jsfiddle.net/rgvj1nca/

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

1 Comment

yeah, and it's even cleaner if you use booleans for the conditions as @davide-lorenzo-marino pointed out
0

You can use boolean values to simplify the code

<div ng-app='app' ng-init='value = false;' ng-controller="myctrl">
   <h1 ng-click="value = !value; event.PreventDefault;">Toggle</h1>
   <h3 ng-show="value" >{{var1}}</h1>
   <h3 ng-show="!value" >{{var2}}</h1>  
</div>

<script>
(function () {
'use strict';

angular.module('app', [])
.controller('myctrl', myctrl);

function myctrl($scope){
  $scope.var1 = "Its on";
  $scope.var2 = "Its off";
}
})();
</script>

Comments

0

You can use single variable and toggle it's value in controller. This way the implementation is very clean and the you are not introducing a lot of variables

<body>
<div ng-app='app' ng-controller="myctrl">
  <h1 ng-click="toggleValue()">Toggle</h1>
    <h3>{{var1 ? 'Its on' : 'Its of' }}</h3>
  </h1>
</div>

<script>
  (function () {
    'use strict';

   angular.module('app', [])
    .controller('myctrl', myctrl);

   function myctrl($scope){

     $scope.toggleValue = function () {
       $scope.var1 = !$scope.var1;
     };

   }
  })();
</script>
</body>

See the working implementation in this JSBin: https://jsbin.com/tihiru/1/edit?html,js,console,output

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.