- AngularJS入门与进阶
- 江荣波
- 278字
- 2020-11-28 23:44:35
6.5 $location实现多视图切换
在前面的案例中,我们都是通过超链接的形式改变浏览器地址栏URL,从而达到视图切换的效果。本节我们将以一个案例说明如何使用$location服务实现视图的切换。
代码清单:ch06\ch06_05.html
<!doctype html> <html ng-app=”routeModule”> <head> <meta charset=”UTF-8”> <title>ch06_05</title> <script src=”/angular-1.5.5/angular.js”></script> <script src=”/angular-1.5.5/angular-route.js”></script> </head> <body ng-controller=”MultiViewController”> <div> <button ng-click=”goView1()">view1</button> <button ng-click=”goView2()">view2</button> </div> <div ng-view></div> <script type=”text/ng-template” id=”/view1.html”> <h1>View1内容<h1> </script> <script type=”text/ng-template” id=”/view2.html”> <h1>View2内容<h1> </script> <script> var routeModule = angular.module('routeModule', ['ngRoute']) routeModule.config(['$routeProvider', function($routeProvider){ $routeProvider. when('/view1', { templateUrl: '/view1.html' }). when('/view2', { templateUrl: '/view2.html' }) }]); routeModule.controller("MultiViewController”, function($scope, $location){ $scope.goView1 = function() { $location.path("/view1”); }; $scope.goView2 = function() { $location.path("/view2”); }; }); </script> </body> </html>
在浏览器中运行ch06_05.html,效果如图6.7所示。
图6.7 $location实现多视图切换案例
本例中我们把ch06_03.html中的超链接改成了两个按钮,然后在控制器中响应按钮的单击事件,在事件响应方法中调用$location.path()方法改变浏览器地址栏URL,所以单击两个按钮时同样可以达到视图切换的效果。