When using angularjs, it becomes easy to add attributes to HTML tags. For instance, when displaying a product if it is found or showing a message if not, I find the ng-show
attribute particularly useful. Here's an example:
Using ng-show ensures that you do not affect the URL because the content is already loaded.
HTML:
<html ng-app="productDisplay">
<head>
<title>Product info</title>
<script src="js/angular.js"></script>
<script src="js/app.js"></script>
</head>
<body>
<div id="content" ng-controller="ProductController as productCtrl">
<div ng-show="status === 'waiting'">
<p>waiting for product to load..</p>
</div>
<div ng-show="status === 'found'">
<!-- display product info here -->
<p>Name: {{ product.name }}</p>
<p>Price: {{ product.price }}</p>
</div>
<div ng-show="status === 'not-found'">
<p style="color: red;">Not found such product</p>
</div>
</div>
</body>
</html>
JS:
(function() {
// Can only access variable app within this function scope
var app = angular.module('productDisplay', []);
app.controller('ProductController', ['$scope', function($scope) {
$scope.product = {name: '', price: ''};
$scope.status = 'waiting';
this.getProduct = function() {
found = false;
/** Some code checking if product found */
if (!found) {
$scope.status = 'not-found';
return {};
} else {
$scope.status = 'found';
return {name: 'BBB', price: '123$'};
}
};
$scope.product = this.getProduct();
}]);
})();