AngularJS page jump Route instance code

  • 2021-08-03 08:41:28
  • OfStack

AngulagJs pages use Route jumps

1. In addition to referencing AngularJs. js, also refer to the route JS, "~/Scripts/angularjs/angular-route. js"

2. Defining a route through $routeProvider, example


var testModule = angular.module('testModule', ['ngRoute']);

testModule.config(['$routeProvider', function ($routeProvider) {
 $routeProvider.when('/2', {//'/2' Defined routing path, which is accessed later, usually defined as a short path 
  templateUrl: "/home/index2",//"/home/index2" Is the path to which the actual access is routed, which can be asp.net mvc The access path of (this example), or the specific page path, such as " test/test.html"
  controller:'testController'// Routing jump controller, You must define this controller later 
 });

 $routeProvider.when('/3', {
  templateUrl: "/home/index3",
  controller:'testController'
 })

}]);

3. Use route jump and combine ng-view to make spa

3.1 Jump with $location in JS, as in the example, by calling goToIndex2 when needed


testModule.controller("testController", ["$scope", "$location", function ($scope, $location) {

 $scope.goToIndex2 = function () {
  $location.path("/2")
 }
}]);

3.2 Use href= "# path" to jump in html code


<html >
<head>
 <meta name="viewport" content="width=device-width" />
 <title>Index1</title>
 @Styles.Render("~/Content/css/base")
 @Scripts.Render("~/script/base")
 <script src="~/scripts/ngmoudle/app.js"></script>
</head>
<body>
 <div ng-app="testModule" ng-controller="testController">
  <header>
   <h1>This is Index1</h1>
   <button type="button" class="btn btn-default" ng-click="goToIndex2()">Index2</button>
   <a href="#/3" class="btn btn-default">Index3</a><!-- Pass heft="#path" Jump in the mode -->
   <a href="#/2" class="btn btn-default" >Index2</a>
    </header>
  <div ng-view>

  </div>
  <footer>PAGE FOOTER</footer>
 </div>
</body>
</html>

4. Problems that have to be said about Angularjs version (additional part), "/" changed to "% 2F"

After the new project directly uses Nuget to obtain Angularjs, it is found that according to the above writing, it can't jump, and the symptoms are as follows < a href="#/2" > Index2 < /a > After clicking, it was found that the browser address changed to "#% 22" and "/" changed to "% 2F", which caused the route to fail to jump. After a quick investigation and debugging, it was found that AngularJs had made special treatment for the address since version 1.6. After knowing the reason, it was very simple to solve the problem, and it was declared in Angular that it could be used back to the old way.

See http://stackoverflow.com/questions/41211875/angularjs-1-6-0-latest-now-routes-not-working


testModule.config(['$locationProvider', function($locationProvider) {
 $locationProvider.hashPrefix('');
}]);

testModule.config(['$locationProvider', function($locationProvider) { $locationProvider.hashPrefix(''); }]);

Related articles: