UI 라우터를 사용하여 현재 상태 이름 노출
언어 전환기를 구현하려고 합니다.사용자가 "en"쪽의 특정 페이지에서 "de"를 클릭하면 "de"쪽 페이지로 이동합니다.$state 파라미터를 console.dir하면 지정된 $state의 "current" 속성과 함께 원하는 값이 표시됩니다.$state.current를 console.dir하여 원하는 값에 초점을 맞추려고 하면 부모 상태 속성만 표시됩니다(현재 뷰는 중첩됨).
현재 생각으로는 url/en/content를 사용하고 있습니다.그러면 언어 네비게이션으로 적절한 수신처를 데이터 속성에 동적으로 로드하고 커스텀 디렉티브를 사용하여 원하는 언어 값을 각 변환마다 설정할 수 있습니다.
현시점에서의 중요한 문제는 $state 이름을 공개하는 것입니다.- 다시 말씀드리지만 $state를 단순히 참조할 때 현재 오브젝트는 원하는 값을 제공하지만 $current.state는 직접 부모 상태만 제공합니다.
만약 누군가가 이것을 어떻게 해야 하는지에 대해 더 나은 제안을 한다면, 나는 기꺼이 제안을 받아들인다.
감사합니다!
업데이트! 코드 샘플:
내 상태의 객체 참조:
var urlStates = {
        en: {
            home: {
                name: 'home',
                url: '/en',
                templateUrl: 'templates/'+lang+'/home.html',
                abstract: 'true'
            },
            home_highlights: {
                name:'home.highlights',
                url: '',
                templateUrl: 'templates/'+lang+'/home.highlights.html'
            },
            home_social:
            {
                name: 'home.social',
                url: '/social',
                templateUrl: 'templates/'+lang+'/home.social.html'
            },
            home_map:
            {
                name: 'home.map',
                url: '/map',
                templateUrl: 'templates/'+lang+'/home.map.html'
            }
        };
 
내 상태:
$stateProvider
        .state(urlStates.en.home)
        .state(urlStates.en.home_highlights)
        .state(urlStates.en.home_social)
        .state(urlStates.en.home_map);
        $locationProvider.html5Mode(true);
})
 
컨트롤러:
.controller('LandingPage', function($translate, $state){
    this.state = $state;
    this.greeting = "Hello";
});
 
마지막으로 돔에서 볼 수 있는 출력은 다음과 같습니다.
this.state = $state;
{
    "params": {},
    "current": {
        "name": "home.highlights",
        "url": "",
        "templateUrl": "templates/en/home.highlights.html" },
        "transition": null
}
 
this.state = $state.current의 경우
{
    "name": "",
    "url": "^",
    "views": null,
    "abstract": true
}
나는 이렇게 한다
자바스크립트:
var module = angular.module('yourModuleName', ['ui.router']);
module.run( ['$rootScope', '$state', '$stateParams',
                      function ($rootScope,   $state,   $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams; 
}
]);
 
HTML:
<pre id="uiRouterInfo">
      $state = {{$state.current.name}}
      $stateParams = {{$stateParams}}
      $state full url = {{ $state.$current.url.source }}    
</pre>
 
예
http://plnkr.co/edit/LGMZnj?p=preview
이 형식으로 질문에 대답하는 것은 매우 어렵습니다.
반면에 내비게이션에 대해 묻고 다음으로 현재에 대해 묻습니다.$state이상하게 행동해요.
첫 번째는 너무 광범위한 질문이고 두 번째는...뭔가 잘못하고 있거나 당연한 것을 놓치고 있습니다.
다음 컨트롤러를 사용합니다.
app.controller('MainCtrl', function($scope, $state) {
  $scope.state = $state;
});
 
어디에app는 다음과 같이 설정됩니다.
app.config(function($stateProvider) {
  $stateProvider
    .state('main', {
        url: '/main',
        templateUrl: 'main.html',
        controller: 'MainCtrl'
    })
    .state('main.thiscontent', {
        url: '/thiscontent',
        templateUrl: 'this.html',
        controller: 'ThisCtrl'
    })
    .state('main.thatcontent', {
        url: '/thatcontent',
        templateUrl: 'that.html'
    });
});
 
그 후, 심플한 HTML 템플릿은
<div>
  {{ state | json }}
</div>
 
예를 들어, 다음과 같이 「인쇄」할 수 있습니다.
{ 
  "params": {}, 
  "current": { 
    "url": "/thatcontent", 
    "templateUrl": "that.html", 
    "name": "main.thatcontent" 
  }, 
  "transition": null
}
 
제가 이걸 보여주는 작은 예를 하나 들어봤습니다.ui.router그리고.pascalprecht.translate메뉴판입니다.유용하다고 생각하고, 당신이 무엇을 잘못하고 있는지 알아내길 바랍니다.
여기 http://plnkr.co/edit/XIW4ZE에서 확인하세요.
스크린 캡
현재 프로젝트에서 솔루션은 다음과 같습니다.
추상적인 언어 상태를 만들었습니다.
$stateProvider.state('language', {
    abstract: true,
    url: '/:language',
    template: '<div ui-view class="lang-{{language}}"></div>'
});
 
프로젝트의 모든 상태는 이 상태에 의존해야 합니다.
$stateProvider.state('language.dashboard', {
    url: '/dashboard'
    //....
});
 
언어 스위치 버튼은 커스텀 함수를 호출합니다.
<a ng-click="footer.setLanguage('de')">de</a>
 
대응하는 기능은 다음과 같습니다(물론 컨트롤러 내부).
this.setLanguage = function(lang) {
    FooterLog.log('switch to language', lang);
    $state.go($state.current, { language: lang }, {
        location: true,
        reload: true,
        inherit: true
    }).then(function() {
        FooterLog.log('transition successfull');
    });
};
 
이것은 동작합니다만, 상태 파라미터의 값을 html에서 변경하는 것만으로, 보다 좋은 솔루션이 있습니다.
<a ui-sref="{ language: 'de' }">de</a>
 
유감스럽게도 이 방법은 동작하지 않습니다.https://github.com/angular-ui/ui-router/issues/1031 를 참조해 주세요.
타임아웃 사용
$timeout(function () { console.log($state.current, 'this is working fine'); }, 100);
 
참조 - https://github.com/angular-ui/ui-router/issues/1627
$state위에 $timeout나한테는 효과가 있었어요
예를들면,
(function() {
  'use strict';
  angular
    .module('app')
    .controller('BodyController', BodyController);
  BodyController.$inject = ['$state', '$timeout'];
  /* @ngInject */
  function BodyController($state, $timeout) {
    $timeout(function(){
      console.log($state.current);
    });
  }
})();
로드 시간 때문에 각도가 현재 상태를 알려 줍니다.
를 사용하여 $timeout 이 는 이 함수에 맞는  수 .$state.current.name
$timeout(function(){
    $rootScope.currState = $state.current.name;
})
언급URL : https://stackoverflow.com/questions/25370775/exposing-the-current-state-name-with-ui-router
'programing' 카테고리의 다른 글
| 스냅샷을 생성할 때 Jest/Enzym ShowlowWrapper가 비어 있습니다. (0) | 2023.03.23 | 
|---|---|
| 스프링 부트 내의 /info 엔드포인트에 프로그래밍 방식으로 추가하는 방법은 무엇입니까? (0) | 2023.03.23 | 
| Spring Crud Repository를 사용한 대소문자를 구분하지 않는 쿼리 (0) | 2023.03.23 | 
| ng-if in react.js에 해당하는 것은 무엇입니까? (0) | 2023.03.23 | 
| 여러 워크시트를 사용하여 PHPexcel 기존 .xlsx 파일 수정 (0) | 2023.03.23 |