AngularJS: creare uno switch per le view

AngularJS: creare uno switch per le view

Creare uno switch per le view di un app è semplice in AngularJS.

Innanzitutto creiamo un controller che gestisca le view:


var app = angular.module('MyApp',[]);

app.controller('MyCtrl', ['$scope', function($scope) {
	$scope.currentView = 'Home';

	$scope.changeView = function(view) {
		$scope.currentView = view;
	};
}]);

Quindi usiamo la direttiva ng-switch insieme con la direttiva ng-include:


<div ng-controller="MyCtrl">
	<nav>
		<a href="" ng-click="changeView('Home')">Home</a>
		<a href="" ng-click="changeView('About')">About</a>
		<a href="" ng-click="changeView('Profile')">Profile</a>
	</nav>
    <div ng-switch on="currentView">
         <div ng-switch-when="Home">
             <div ng-include="'views/home.html'"></div>
         </div>
         <div ng-switch-when="About">
            <div ng-include="'views/about.html'"></div>
         </div>
         <div ng-switch-when="Profile">
            <div ng-include="'views/profile.html'"></div>
         </div>
      </div>
</div>

Torna su