English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

AngularJs ng-route 라우팅 자세히 설명 및 예제 코드

전제

먼저 페이지에 angular과 angular을 가져오는 것이 필요합니다.-route를 주의해야 합니다. angular-route가 angular을 선언하기 전에

<script src="../../bower_components/angular/angular.js"></script>
<script src="../../bower_components/angular-route/angular-route.js"></script>

이는 주로 angular-route.js에 window.angular이라는 매개변수를 전달해야 하며, 이 매개변수는 angular이 로드된 후에만 나타납니다.

(function(window, angular, undefined) {
"use strict";
...
ngRouteModule.directive('ngView', ngViewFactory);
...
})(window, window.angular);

다운로드는 공식 웹사이트에서 다운로드하거나 bower를 사용하여 설치할 수 있습니다.

설명

  라우팅 기능은 routeProvider 서비스와 ng-view와 함께 구현됩니다, ng-view는 페이지 템플릿의 마운팅 포인트로서, URL을 탐색하여 점프할 때, 다른 페이지 템플릿이 ng-view 위치; 그런 다음 routeProvider를 통해 라우팅 매핑을 설정합니다.

일반적으로 두 가지 메서드를 통해 설정됩니다:

when(): 경로와 파라미터를 설정합니다;

otherwise: 다른 경로 점프를 설정할 수 있습니다. default로 생각할 수 있습니다.

when의 두 번째 파라미터:

controller: 해당 경로의 컨트롤러 함수 또는 이름

controllerAs: 컨트롤러에 별명을 지정합니다

template: 해당 경로의 페이지 템플릿, ng-view 위치에, 예를 들어 "<div>xxxx</div>"

templateUrl: 해당 템플릿의 경로, 예를 들어 "src/xxx.html"

resolve: 이 파라미터에 대해 자세히 설명하겠습니다. 이 속성은 키밸류 오브젝트 형태로 라우팅 관련 컨트롤러에 서비스나 값을 바인딩합니다. 그런 다음 실행 결과 값이나 해당 서비스 참조를 컨트롤러에 주입합니다. resolve에 promise 객체가 있을 경우, 그것이 성공적으로 실행되면 컨트롤러에 주입됩니다. 이 때 컨트롤러는 resolve의 실행 결과를 기다립니다.

상세한 예제는 아래의 예제를 참고하세요.

redirectTo: 재정향 주소

reloadOnSearch: 주소가 변경되었을 때만 해당 템플릿을 로드할지 설정합니다; search와 params 변경 시 템플릿을 로드하지 않습니다

caseInsensitiveMatch: 경로는 대소문자를 구분하지 않습니다

라우팅에는 몇 가지 일반적인 이벤트가 있습니다:

$routeChangeStart: 이 이벤트는 라우팅 점프 전에 발생합니다

$routeChangeSuccess: 이 이벤트는 라우팅 점프 성공 후 발생합니다

$routeChangeError: 이 이벤트는 라우팅 점프 실패 후 발생합니다

사용

페이지에서, URL 점프 버튼 링크를 입력하고 ng-view 태그  

 <div ng-controller="myCtrl">
  <ul>
   <li><a href="#/a">click a</a></li>
   <li><a href="#/b">click b</a></li>
  </ul>
  <ng-view></ng-view>
  !<-- <div ng-view ></div> -->
 </div>

중에서, ng-view는 요소나 태그와 같이 사용할 수 있습니다.

javascript에서 점프 설정을 정의해야 합니다.

<script type="text/javascript">
 angular.module("myApp",["ngRoute"])
 .controller("aController",function($scope,$route){
  $scope.hello = "hello,a!";
 })
 .controller("bController",function($scope){
  $scope.hello = "hello,b!";
 })
 .controller("myCtrl",function($scope,$location){
  $scope.$on("$viewContentLoaded",function(){
   console.log("ng-view content loaded!);
  });
  $scope.$on("$routeChangeStart",function(event,next,current){
   //event.preventDefault(); //cancel url change
   console.log("route change start!");
  });
 })
 .config(function($routeProvider, $locationProvider) {
   $routeProvider
   .when('/a', {
   templateUrl: 'a.html',
   controller: 'aController'
   })
  .when('/b', {
   templateUrl: 'b.html',
   controller: 'bController',
   resolve: {
     // I will cause a 3 second delay
     delay: function($q, $timeout) {
     var delay = $q.defer();
     $timeout(delay.resolve, 3000);
     return delay.promise;
     }
   }
  })
  .otherwise({
   redirectTo: '/a'
   });
 });
 </script>

위의 코드에서,/b 경로에서 resolve와 연결된 지연 메서드를 하나 추가하였으며, 이 메서드는 Promise 객체를 반환하는3초 후에 결과를 반환합니다. 따라서 b 페이지는3초 후에 로드됩니다. 따라서 b 페이지는

추가로 두 개의 html 파일을 제공해야 합니다:

a.html을 포함하여:

<div ng-controller="aController" style="height:500px;width:100%;background-color:green;">{{hello}}</div>

또한 b.html을 포함하여:

<div ng-controller="bController" style="height:2500px;width:100%;background-color:blue;">{{hello}}</div>

이렇게 하면 라우팅의 이동을 구현할 수 있습니다.

전체 코드는 다음과 같습니다:

<html ng-app="myApp">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <script src="../../bower_components/angular/angular.js"></script>
 <script src="../../bower_components/angular-route/angular-route.js"></script>
</head>
<body>
 <div ng-controller="myCtrl">
  <ul>
   <li><a href="#/a">click a</a></li>
   <li><a href="#/b">click b</a></li>
  </ul>
  <ng-view></ng-view>
  !<-- <div ng-view ></div> -->
 </div>
 <script type="text/javascript">
 angular.module("myApp",["ngRoute"])
 .controller("aController",function($scope,$route){
  $scope.hello = "hello,a!";
 })
 .controller("bController",function($scope){
  $scope.hello = "hello,b!";
 })
 .controller("myCtrl",function($scope,$location){
  $scope.$on("$viewContentLoaded",function(){
   console.log("ng-view content loaded!);
  });
  $scope.$on("$routeChangeStart",function(event,next,current){
   //event.preventDefault(); //cancel url change
   console.log("route change start!");
  });
 })
 .config(function($routeProvider, $locationProvider) {
   $routeProvider
   .when('/a', {
   templateUrl: 'a.html',
   controller: 'aController'
   })
  .when('/b', {
   templateUrl: 'b.html',
   controller: 'bController',
   resolve: {
     // I will cause a 1 second delay
     delay: function($q, $timeout) {
     var delay = $q.defer();
     $timeout(delay.resolve, 3000);
     return delay.promise;
     }
   }
  })
  .otherwise({
   redirectTo: '/a'
   });
 });
 </script>
</body>
</html>

위는 AngularJS ng-route 라우트 자료 정리, 이후 추가 자료를 보충할 예정입니다. 많은 지원에 감사합니다!

안내: 본 문서의 내용은 인터넷에서 가져왔으며, 저작권은 원 저자에게 있으며, 인터넷 사용자가 자발적으로 기여하고 업로드한 내용입니다. 이 사이트는 소유권을 가지지 않으며, 인공 편집을 하지 않았으며, 관련 법적 책임을 부담하지 않습니다. 저작권 침해가 의심되는 내용이 있으시면 notice#w 이메일로 문의해 주세요.3codebox.com에 (이메일 작성 시 #을 @으로 변경하여) 신고를 하시고 관련 증거를 제공하시면, 사실이 확인되면 이 사이트는 즉시 저작권 침해 내용을 삭제합니다.

좋아하는 것