AngularJS에서 쿼리 파라미터를 읽는 가장 간결한 방법은 무엇입니까?
AngularJs를 사용하여 URL 쿼리 파라미터 값을 읽고 싶습니다.다음 URL로 HTML에 접속하고 있습니다.
http://127.0.0.1:8080/test.html?target=bob
★★★★★location.search"?target=bob"타겟의 값에 액세스 하기 위해서, Web에 리스트 되고 있는 다양한 예를 찾았습니다만, 어느 것도 AngularJS 1.0.0rc10에서는 동작하지 않습니다.특히, 이하가 전부입니다.undefined:
$location.search.target$location.search['target']$location.search()['target']
$location★★★★★★★★★★★★★★★★★★★★★★★★★★」
업데이트:
아래에 솔루션을 게시했지만 완전히 만족하지는 않습니다.Developer Guide: Angular Services: (개발자 가이드: Angular Services: $location을 사용하면 다음 정보가 나타납니다.$location:
$location은 언제 사용해야 합니까?
응용 프로그램이 현재 URL 변경에 응답해야 하거나 브라우저에서 현재 URL을 변경해야 할 경우.
이 시나리오에서는 쿼리 파라미터를 사용하여 외부 웹 페이지에서 페이지가 열리기 때문에 "현재 URL 변경에 반응"하는 것 자체가 아닙니다. 아마 ★★★★★★★★★★★★★★★★★★★.$location이 작업에 적합한 도구가 아닙니다(추악한 자세한 내용은 아래 답변 참조).이 을 ' in to read query parameters in Angular.$장소?【JSJS에서 쿼리 파라미터를 읽는 가장 간결한 방법은 무엇입니까?"로 지정합니다.하여 【javascript】를 해석할 수 .location.search하지만 기본적인 것에 대해 그렇게 낮은 수준을 유지하는 것은 내 프로그래머의 감성을 정말 거슬리게 한다.
더 요?$location니면 간간 ?안 안? ???
컨트롤러에 $routeParams(ngRoute 필요)를 삽입할 수 있습니다.다음은 문서의 예입니다.
// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
편집: $location 서비스를 사용하여 쿼리 파라미터를 취득 및 설정할 수도 있습니다(다음 URL에서 이용 가능).ng ), 특 ), ), 。search메서드: $location.검색 »
로드 후 $Params는 하지 않습니다route Params는 그렇지 않습니다.$location.search()언제든지 호출할 수 있습니다.
html5 모드로 동작할 수 있게 되어 다행이지만 해시방 모드로 동작시킬 수도 있습니다.
다음과 같이 간단하게 할 수 있습니다.
$location.search().target
'target' 검색 매개 변수에 액세스합니다.
참고로 작업 중인 jsFiddle은 다음과 같습니다.http://web.archive.org/web/20130317065234/http : //jsfiddle.net/PHnLb/7/
var myApp = angular.module('myApp', []);
function MyCtrl($scope, $location) {
$scope.location = $location;
$scope.$watch('location.search()', function() {
$scope.target = ($location.search()).target;
}, true);
$scope.changeTarget = function(name) {
$location.search('target', name);
}
}
<div ng-controller="MyCtrl">
<a href="#!/test/?target=Bob">Bob</a>
<a href="#!/test/?target=Paul">Paul</a>
<hr/>
URL 'target' param getter: {{target}}<br>
Full url: {{location.absUrl()}}
<hr/>
<button ng-click="changeTarget('Pawel')">target=Pawel</button>
</div>
저만의 질문에 부분적으로 대답하기 위해 HTML5 브라우저의 작업 샘플을 다음에 제시하겠습니다.
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script>
<script>
angular.module('myApp', [], function($locationProvider) {
$locationProvider.html5Mode(true);
});
function QueryCntl($scope, $location) {
$scope.target = $location.search()['target'];
}
</script>
</head>
<body ng-controller="QueryCntl">
Target: {{target}}<br/>
</body>
</html>
열쇠는 전화하는 것이었다.$locationProvider.html5Mode(true);위와 같이열 때 작동하게 되었습니다.http://127.0.0.1:8080/test.html?target=bob오래된 브라우저에서는 동작하지 않는 것이 마음에 들지 않지만, 어쨌든 이 방법을 사용할지도 모릅니다.
오래된 브라우저에서 사용할 수 있는 대안은 이 기능을 해제하는html5mode(true)대신 다음 주소를 hash+syslog와 함께 사용합니다.
http://127.0.0.1:8080/test.html#/?target=bob
관련 매뉴얼은 Developer Guide: Angular Services: $location 사용(이상하게도 구글 검색에서 찾을 수 없었습니다...)
다음 두 가지 방법으로 수행할 수 있습니다.
- 사용.
$routeParams
권장되는 최선의 솔루션은$routeParams컨트롤러에 접속합니다.필요한 것은ngRoute모듈을 장착합니다.
function MyController($scope, $routeParams) {
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
// $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
var search = $routeParams.search;
}
- 사용.
$location.search().
여기에 주의사항이 있습니다.HTML5 모드에서만 동작합니다.디폴트로는 해시가 없는 URL에서는 동작하지 않습니다.#)이 포함되어 있습니다.http://localhost/test?param1=abc¶m2=def
다음을 추가하여 작동시킬 수 있습니다.#/를 참조해 주세요.http://localhost/test#/?param1=abc¶m2=def
$location.search()다음과 같은 개체를 반환합니다.
{
param1: 'abc',
param2: 'def'
}
$location.search()는 HTML5 모드가 켜져 있고 지원되는 브라우저에서만 작동합니다.
이 조작은 항상 유효합니다.
$138.location.서치
여름을 즐기려고.
외부 링크에서 앱을 로드하는 경우 angular는 URL 변경으로 이를 감지하지 않으므로 $loaction.search()를 지정하면 빈 객체가 나타납니다.이를 해결하려면 앱 구성(app.js)에서 다음을 설정해야 합니다.
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider)
{
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}]);
엘리스 화이트헤드의 대답에 딱 들어맞는군요 $locationProvider.html5Mode(true);응용 프로그램의 기본 URL을 지정하지 않으면 angularjs의 새 버전에서 작동하지 않습니다.<base href=""> requireBase로로 합니다.false
문서에서:
html5Mode(history.pushState)를 사용하도록 $location을 설정하는 경우 태그로 응용 프로그램의 기본 URL을 지정하거나 requireBase:false를 가진 정의 개체를 $locationProvider.html5Mode()로 전달하여 기본 태그를 요구하지 않도록 $locationProvider를 설정해야 합니다.
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$location을 사용할 수도 있습니다.$$search.당신의 파라미터
SPA HTML5 Mode의 경우 404개의 에러 문제가 발생하므로 $location을 작성할 필요가 없습니다.검색 작업을 수행합니다.내 경우 사용자가 내 사이트에 왔을 때 URL 쿼리 문자열 파라미터를 캡처하고 사용자가 처음 링크한 "페이지"에 관계없이 로그인한 후 해당 페이지로 전송할 수 있도록 합니다.그래서 앱에 있는 모든 것을 캡처합니다.
$rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams) {
if (fromState.name === "") {
e.preventDefault();
$rootScope.initialPage = toState.name;
$rootScope.initialParams = toParams;
return;
}
if ($location.search().hasOwnProperty('role')) {
$rootScope.roleParameter = $location.search()['role'];
}
...
}
로그인 후에 $state.go($rootScope.initialPage, $rootScope.initialParams)라고 말할 수 있습니다.
조금 늦었지만, 당신의 문제는 당신의 URL이었던 것 같습니다.
http://127.0.0.1:8080/test.html?target=bob
가지고 있었다
http://127.0.0.1:8080/test.html#/?target=bob
효과가 있었을 거라고 확신해요Angular는 그 #/에 대해 매우 까다롭다.
언급URL : https://stackoverflow.com/questions/11063673/whats-the-most-concise-way-to-read-query-parameters-in-angularjs
'source' 카테고리의 다른 글
| 비즈니스 논리: 데이터베이스 또는 애플리케이션 계층 (0) | 2023.03.11 |
|---|---|
| 스프링 부트: 프리픽스가 다른 여러 유사한 Configuration Properties (0) | 2023.03.11 |
| Python에서 두 개의 json 문자열을 병합하는 방법은 무엇입니까? (0) | 2023.03.11 |
| 오브젝트 속성 정렬 및 JSON.stringify (0) | 2023.03.11 |
| 모든 뷰 로드 완료 후 Javascript 실행 (0) | 2023.03.11 |