Monday, 25 April 2016

How to use ng-show and ng-hide directives ?


Using directives ng-show and ng-hide

myapp.js
Data model having a flag with boolean value.
(function(){
  var myapp = angular.module('module1', []);

  myapp.controller('moduleController1', function(){
      this.product = car;
  });

  var car = {
    name: 'Car',
    price: 800000,
    desc: '4 wheeler',
    isPurchasable: true,
    isOutOfStock: false
  }
})();


Web page including ng-show using the flag at 2 places : One for positive test another for negative test.

  <body ng-controller="moduleController1 as c1">
    <div ng-show="!c1.product.isOutOfStock">
       <h1>{{c1.product.name}}</h1>
       <h1>{{c1.product.price}}</h1>
       <p>{{c1.product.desc}}</p>
       <button ng-show="c1.product.isPurchasable">Buy now</button>
    </div>
    <script type="text/javascript" src="angular.min.js"> </script>
    <script type="text/javascript" src="myapp.js"> </script>
  </body>



ng-hide directive is better and preferred to use for negative test.
    <div ng-show="!c1.product.isOutOfStock">

is equivalant to :
    <div ng-hide="c1.product.isOutOfStock">

No comments:

Post a Comment

Note: only a member of this blog may post a comment.