>  기사  >  웹 프론트엔드  >  ui-route를 사용하여 AngularJS에서 다층 중첩 라우팅 구현(자세한 튜토리얼)

ui-route를 사용하여 AngularJS에서 다층 중첩 라우팅 구현(자세한 튜토리얼)

亚连
亚连원래의
2018-06-12 17:10:071664검색

이 기사에서는 주로 ui-route를 사용하여 다중 계층 중첩 라우팅을 구현하는 AngularJS의 예를 소개하고 참고용으로 제공합니다.

이 기사에서는 ui-route를 사용하여 다중 계층 중첩 라우팅을 구현하는 예를 소개합니다. 자세한 내용은 다음과 같습니다.

1. 기대되는 구현 효과:

https: //liyuan-meng.github.io/ uiRouter-app/index.html

(프로젝트 주소: https://github.com/liyuan-meng/uiRouter-app)

둘째, 질문 요구사항을 분석하고, 종속성 및 프로젝트 빌드

1. 서비스:

(1) 조건에 따라 사용자 데이터 checkPeople.service를 쿼리하거나 조건이 지정되지 않은 경우 모두 쿼리합니다.

(2) 라우팅 정보 getStateParams.service를 가져옵니다.

2. 구성 요소:

(1) 안녕하세요 모듈: 버튼을 클릭하면 내용이 변경됩니다.

(2) peopleList 모듈: 사람 목록을 표시합니다. 사람을 클릭하면 사람 세부 정보가 표시됩니다. checkPeople.service 모듈에 따라 다릅니다.

(3) peopleDetail 모듈: 사람 세부정보를 표시하고 checkPeople.service 모듈 및 getStateParams.service 모듈을 사용합니다.

3. 프로젝트 빌드:

그림과 같이 컴포넌트 디렉터리는 모든 서비스 모듈과 비즈니스 모듈을 저장하는 데 사용되며, lib 디렉터리는 외부 참조를 저장하는 데 사용됩니다(저는 angle.js1을 사용합니다. 5.8 및 ui-route0.2.18), app.config.js 파일은 라우팅 구성에 사용되며 index.html은 항목 파일로 사용됩니다.

3. 이 예제를 구현합니다

1. 홈페이지 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="./lib/angular.js"></script>
  <script src="./lib/angular-ui-route.js"></script>
  <script src="./app.config.js"></script>
  <script src="./components/core/people/checkPeople.service.js"></script>
  <script src="./components/core/people/getStateParams.service.js"></script>
  <script src="./components/hello/hello.component.js"></script>
  <script src="./components/people-list/people-list.component.js"></script>
  <script src="./components/people-detail/people-detail.component.js"></script>
</head>
<body ng-app="helloSolarSystem">
<p>
  <a ui-sref="helloState">Hello</a>
  <a ui-sref="aboutState">About</a>
  <a ui-sref="peopleState">People</a>
</p>

<ui-view></ui-view>

</body>
</html>

(1) lib에 있는 파일과 사용된 모든 서비스 및 구성 요소 서비스 파일을 가져옵니다.

(2) ng-app="helloSolarSystem"은 helloSolarSystem 모듈에서 구문 분석이 시작되도록 지정합니다.

(3) 뷰 정의 5643c5c8ec46989a1440c123e54787f3142226fc0f7a4611fbee3f36258ad78a

2. 라우팅 app.config.js

&#39;use strict&#39;;

angular.module("helloSolarSystem", [&#39;peopleList&#39;, &#39;peopleDetail&#39;, &#39;hello&#39;,&#39;ui.router&#39;]).

  config([&#39;$stateProvider&#39;, function ($stateProvider) {

    $stateProvider.state(&#39;helloState&#39;, {
      url: &#39;/helloState&#39;,
      template:&#39;<hello></hello>&#39;

    }).state(&#39;aboutState&#39;, {
      url: &#39;/about&#39;,
      template: &#39;<h4>Its the UI-Router Hello Solar System app!</h4>&#39;

    }).state(&#39;peopleState&#39;, {
      url: &#39;/peopleList&#39;,
      template:&#39;<people-list></people-list>&#39;

    }).state(&#39;peopleState.details&#39;, {
      url:&#39;/detail/:id&#39;,
      template: &#39;<people-detail></people-detail>&#39;
    })
  }
]);

(1) 모듈 이름: helloSolarSystem 구성

(2) 'peopleList' 삽입 ', 'peopleDetail', 'hello', 'ui.router' 모듈입니다.

(3) helloState라는 첫 번째 뷰 컨트롤러와 같은 stateProvider 서비스의 뷰 제어를 구성합니다. ui-sref == "helloState"인 경우 경로는 url #/helloState 및 76423811727f33eb9f37426abd93e311142226fc0f7a4611fbee3f36258ad78a에 표시된 콘텐츠는 5d31ad12eb7f2467fa10436b397d69f6ce2196d7bcfa28427152ee3efb4b3e34 구성요소에 의해 구문 분석된 콘텐츠입니다.

(4) 중첩 라우팅 구현: peopleState라는 뷰 컨트롤러가 상위 경로입니다. peopleState.details라는 뷰 컨트롤러는 하위 경로입니다. 이는 상대 라우팅 방법입니다. 상위 경로는.../index.html#/peopleState/와 일치하고 하위 경로는.../index.html#/peopleState/detail/x와 일치합니다(x는 /detail/입니다. :id 의 id 값). 절대 라우팅으로 변경하는 경우 url:'^/detail/:id'만 작성하면 하위 경로는.../index.html#/detail/x(x는 /detail/에 있음)와 일치합니다. :id) ID 값).

4. checkPeople.service 구현(조건에 따라 사람 찾기)

checkPeople.sercice.js

&#39;use strict&#39;;

//根据条件(参数)查找信息。
angular.module(&#39;people.checkPeople&#39;, [&#39;ui.router&#39;]).
  factory(&#39;CheckPeople&#39;, [&#39;$http&#39;, function ($http) {
    return {
      getData: getData
    };
    function getData(filed) {
      var people;
      var promise = $http({
        method: &#39;GET&#39;,
        url: &#39;./data/people.json&#39;
      }).then(function (response) {
        if (filed) {
          people = response.data.filter(function (value) {
            if (Number(value.id) === Number(filed)) {
              return value;
            }
          })
        } else {
          people = response.data;
        }
        return people;
      });
      return promise;
    }
  }]);

(1) getData 함수에서 사람 정보를 저장하기 위해 배열을 반환하고 싶지만, $http( ).then() 서비스는 비동기식 요청이므로 언제 요청이 종료될지 알 수 없으므로 people 배열을 반환하는 데 문제가 있습니다. $http().then()이 Promise 객체라는 것을 알았으므로 이 객체를 직접 반환하는 것을 생각할 수 있으므로 "function.then(function(data))의 결과"를 사용하여 비동기 요청을 얻을 수 있습니다. 데이터 데이터가 옵니다.

3. getStateParams.service 구현(라우팅 정보 가져오기)

getStatePatams.service.js

"use strict";

angular.module("getStateParams", [&#39;ui.router&#39;]).
  factory("GetStateParams", ["$location", function ($location) {
    return {
      getParams: getParams
    };
    function getParams() {
      var partUrlArr = $location.url().split("/");
      return partUrlArr[partUrlArr.length-1];
    }
}]);

(1) 여기서 getParams 함수는 사람의 ID인 라우팅 정보의 마지막 데이터를 반환합니다. . 은 충분히 다재다능하지 않으며 보다 합리적으로 최적화해야 할 수도 있습니다. 그러나 그것은 우리의 필요에 영향을 미치지 않습니다.

4. hello 모듈 구현

hello.template.html

<p>
  <p ng-hide="hideFirstContent">hello solar sytem!</p>
  <p ng-hide="!hideFirstContent">whats up solar sytem!</p>
  <button ng-click="ctlButton()">click</button>
</p>

hello.comComponent.js

&#39;use strict&#39;;

angular.module("hello", [])
  .component(&#39;hello&#39;, {
    templateUrl: &#39;./components/hello/hello.template.html&#39;,
    controller: ["$scope", 
      function HelloController($scope) {
        $scope.hideFirstContent = false;
        $scope.ctlButton = function () {
          this.hideFirstContent = !this.hideFirstContent;
        };
      }
    ]
  });

5. peopleList 모듈 구현:

peopleList.template.html

<p>
  <ul>
    <a ng-repeat="item in people" ui-sref="peopleState.details({id:item.id})">
      <li>{{item.name}}</li>
    </a>
  </ul>
  <ui-view></ui-view>
</p>

(1) 여기5643c5c8ec46989a1440c123e54787f3 142226fc0f7a4611fbee3f36258ad78a peopleList

peopleList.comComponent.js

&#39;use strict&#39;;

angular.module("peopleList", [&#39;people.checkPeople&#39;])
  .component(&#39;peopleList&#39;, {
    templateUrl: &#39;./components/people-list/people-list.template.html&#39;,
    controller: [&#39;CheckPeople&#39;,&#39;$scope&#39;,
      function PeopleListController(CheckPeople, $scope) {
        $scope.people = [];
        CheckPeople.getData().then(function(data){
          $scope.people = data;
        });
      }
    ]
  });

6의 하위 구성요소 pepleDetail을 표시하는 데 사용됩니다. peopleDetail 모듈

peopleDetail.template.html

<ul ng-repeat="item in peopleDetails track by $index">
  <li>名字: {{item.name}}</li>
  <li>介绍: {{item.intro}}</li>
</ul>

peopleDetail.comComponent.js

&#39;use strict&#39;;

angular.module("peopleDetail", [&#39;people.checkPeople&#39;, &#39;getStateParams&#39;])
  .component(&#39;peopleDetail&#39;, {
    templateUrl: &#39;./components/people-detail/people-detail.template.html&#39;,
    controller: [&#39;CheckPeople&#39;, &#39;GetStateParams&#39;, &#39;$scope&#39;,
      function peopleDetailController(CheckPeople, GetStateParams, $scope) {
        $scope.peopleDetails = [];
        CheckPeople.getData(GetStateParams.getParams()).then(function(data){
          $scope.peopleDetails = data;
        });
      }
    ]
  });

위의 내용은 모든 사람을 위해 정리한 내용입니다. 앞으로 모든 사람에게 도움이 되기를 바랍니다.

관련글 :

JS 스크립트 로딩 후 해당 콜백 함수 구현하는 방법

vue+webpack을 사용하여 패키지 파일의 404페이지 공백 문제 해결하는 방법

디버깅 및 독립 구현 방법 webpack 프로젝트를 통한 패키징 구성 파일(자세한 튜토리얼)

vue-cli+webpack 프로젝트를 통해 프로젝트 이름을 수정하는 방법

vue 컴포넌트에서 글로벌 등록과 로컬 등록을 구현하는 방법

위 내용은 ui-route를 사용하여 AngularJS에서 다층 중첩 라우팅 구현(자세한 튜토리얼)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.