medev21 medev21 - 5 months ago 20
Javascript Question

show active color when page loads for the first time - AngularJS

So I have two buttons and their role are to show their respective data when one of the buttons is clicked.

<div>
<h1>Ng-show & ng-hide</h1>
<p class="description">Click on the "show"-link to see the content.</p>
<button ng-click="showme=true" ng-class="{activeButton: showme == true}">Show</button>
<button ng-click="showme=false" ng-class="{activeButton: showme == false}">Hide</button>

<div class="wrapper">
<p ng-hide="showme">It will appear here!</p>
<h2 ng-show="showme">This is mah content, yo!</h2>
</div>
</div>


Now, I added the ng-class to show an active color(say 'red') when a button is clicked and the other should go back to it's original color(blue). When the page loads, the first thing I see is the message "It will appear here!". Which is fine but the button that represents("Hide") this message doesn't have the active color red.

How can I set the active color by default when the page loads for the first time to this button? I would like to keep the toggle functionality still, I should be able to click a button and see the active color.

Your help will be appreciated, thanks in advance!

Answer

Null and Undefined Types are strictly equal(==) to themselves and abstractly equal(==) to each other.[Ref]

In your ng-class statements, neither of the condition is being satisfied hence class is not applied. In ng-show/hide, undefined is evaluated as false hence "It will appear here!" is being shown.

Set the value of showme as true in controller

var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope) {
  $scope.showme = false;
})
.activeButton {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <h1>Ng-show & ng-hide</h1>
  <p class="description">Click on the "show"-link to see the content.</p>
  <button ng-click="showme=true" ng-class="{activeButton: showme}">Show</button>
  <button ng-click="showme=false" ng-class="{activeButton: !showme}">Hide</button>

  <div class="wrapper">
    <p ng-hide="showme">It will appear here!</p>
    <h2 ng-show="showme">This is mah content, yo!</h2>
  </div>
</div>