如何确定AngularJS中的活动路由
在这篇文章中,我们将看到如何确定AngularJS中的活动路由,同时通过例子了解基本的实现。
方法:在AngularJS的任何时刻确定哪个是活动路由,这可以通过使用$on()和$location.path()方法来实现。一个事件可以通过使用on()方法编写一个事件处理程序来处理。routeChangeStart是一个事件,当路由变化开始时被触发,所以,这是由rootScope.on()处理的。因此,在这种方式下,每当路由变化开始时,它触发了由on()事件处理程序处理的routeChangeStart,然后$location.path()给出活动路由的值。
语法:
$rootScope.$on('$routeChangeStart', function () {
console.log($location.path())
});
例子:在这里,我们正在显示哪个是活动路由。在on()方法中,将location.path()值初始化为任何AngularJS范围变量,并通过表达式(数据绑定)显示其详细信息。下面是上述方法的实现。
Active_Route.html:
<!DOCTYPE html>
<html>
<head>
<title>Angular JS Active Route</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js">
</script>
</head>
<body style="text-align: center">
<h1 style="color: green">GeeksforGeeks</h1>
<h3>How to determine active route in AngularJS ?</h3>
<p>
<a href="#viewLanguages">View Languages</a>
</p>
<p>
<a href="#viewCourses">View Courses</a>
</p>
<div ng-app="mainApp" ng-controller="GFGController">
<div ng-view></div>
<p>{{ message }}</p>
<p>{{ mylocation }}</p>
</div>
<script>
var mainApp = angular.module('mainApp', ['ngRoute']);
mainApp.config([
'routeProvider',
function (routeProvider) {
routeProvider
.when('/viewLanguages', {
template:
'<p> Details of all languages content ' +
'available at GeeksforGeeks </p>',
})
.when('/viewCourses', {
template:
'<p> Details of all courses available at' +
' GeeksforGeeks</p>',
})
.otherwise({
redirectTo: '/viewLanguages',
});
},
]);
mainApp.controller(
'GFGController',
function (scope, location,rootScope) {
scope.message =
'This page will be used to promote' + ' GeeksforGeeks';
rootScope.on('routeChangeStart', function () {
scope.mylocation =location.path();
});
}
);
</script>
</body>
</html>
输出: