AngularJS Switch Menu

A switch menu is probably one of the most popular UI interactions in the modern web applications. This is basically switching between different layout modes (list or grid), just by the click of a button. This is extremely easy to achieve using AngularJS. In this case the concept of services is used. Services are nothing but objects used for communication with a server, API or another data source. In the example taken by us, our service communicates with Instagram's API, returning an array of most popular photos in the process.

A point to note is that we should include one additional Angular.js file in the page in order for the code to work.

<script src=""></script>

This includes the ngResource module so that we can easily work with AJAX APIs. This file is automatically included in the editor below.

<div ng-app="switchableGrid" ng-controller="SwitchableGridController">
	<div class="bar">
		<!-- These two buttons switch the layout variable,
			 which causes the correct UL to be shown. -->
		<a class="list-icon" ng-class="{active: layout == 'list'}" ng-click="layout = 'list'"></a>
		<a class="grid-icon" ng-class="{active: layout == 'grid'}" ng-click="layout = 'grid'"></a>

	<!-- We have two layouts. We choose which one to show depending on the "layout" binding -->

	<ul ng-show="layout == 'grid'" class="grid">
		<!-- A view with big photos and no text -->
		<li ng-repeat="p in pics">
			<a href="{{}}" target="_blank"><img ng-src="{{p.images.low_resolution.url}}" /></a>

	<ul ng-show="layout == 'list'" class="list">
		<!-- A compact view smaller photos and titles -->
		<li ng-repeat="p in pics">
			<a href="{{}}" target="_blank"><img ng-src="{{p.images.thumbnail.url}}" /></a>

Using services architecture, AngularJS supports the concepts of "Separation of Concerns". Services are functions in JavaScript which are specialized in performing a specific task only. Owing to this property, this makes them a single entity which makes them easy to maintain and test.

Call can be made to the services by controllers, filters based on the requirement. These services are normally injected using dependency injection mechanism present in AngularJS.

There are many inbuilt services in AngularJS. Some of them are $http, $route, $window, $location etc. Each of these services are responsible for a specific task. For example, to get the data from the server we need to make an AJAX call which is done using the $http service. In another example, to define the routing information, the service called $route is used. The inbuilt services in AngularJS always have '$' symbol as the prefix.

Next ConceptOrder Form