AngularJS 동적 라우팅
현재 라우팅이 내장 된 AngularJS 애플리케이션이 있습니다. 작동하고 모든 것이 정상입니다.
내 app.js 파일은 다음과 같습니다.
angular.module('myapp', ['myapp.filters', 'myapp.services', 'myapp.directives']).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', { templateUrl: '/pages/home.html', controller: HomeController });
$routeProvider.when('/about', { templateUrl: '/pages/about.html', controller: AboutController });
$routeProvider.when('/privacy', { templateUrl: '/pages/privacy.html', controller: AboutController });
$routeProvider.when('/terms', { templateUrl: '/pages/terms.html', controller: AboutController });
$routeProvider.otherwise({ redirectTo: '/' });
}]);
내 앱에는 / pages 디렉토리 내에서 새 html 파일을 복사하고 추가 할 수있는 CMS가 내장되어 있습니다 .
동적으로 추가 된 새 파일에 대해서도 라우팅 공급자를 계속 사용하고 싶습니다.
이상적인 세계에서 라우팅 패턴은 다음과 같습니다.
$ routeProvider.when ( '/ pagename ', {templateUrl : '/ pages / pagename .html', 컨트롤러 : CMSController});
따라서 새 페이지 이름이 "contact.html"인 경우 angular가 "/ contact"를 선택하고 "/pages/contact.html"로 리디렉션하고 싶습니다.
이것이 가능할까요?! 그렇다면 어떻게?!
최신 정보
이제 라우팅 구성에 다음이 있습니다.
$routeProvider.when('/page/:name', { templateUrl: '/pages/home.html', controller: CMSController })
내 CMSController에서 :
function CMSController($scope, $route, $routeParams) {
$route.current.templateUrl = '/pages/' + $routeParams.name + ".html";
alert($route.current.templateUrl);
}
CMSController.$inject = ['$scope', '$route', '$routeParams'];
현재 templateUrl을 올바른 값으로 설정합니다.
그러나 이제 새 templateUrl 값으로 ng-view 를 변경하고 싶습니다 . 이것은 어떻게 이루어 집니까?
angular.module('myapp', ['myapp.filters', 'myapp.services', 'myapp.directives']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/page/:name*', {
templateUrl: function(urlattr){
return '/pages/' + urlattr.name + '.html';
},
controller: 'CMSController'
});
}
]);
- *를 추가하면 여러 수준의 디렉토리에서 동적으로 작업 할 수 있습니다 . 예 : / page / cars / selling / list 는이 제공 업체에서 포착됩니다.
문서 (1.3.0)에서 :
"templateUrl이 함수 인 경우 다음 매개 변수를 사용하여 호출됩니다.
{Array.}-현재 경로를 적용하여 현재 $ location.path ()에서 추출한 경로 매개 변수 "
또한
when (path, route) : 방법
- 경로는 콜론으로 시작하고 별표로 끝나는 명명 된 그룹을 포함 할 수 있습니다 : 예 : 이름 *. 모든 문자는 경로가 일치 할 때 주어진 이름으로 $ routeParams에 열심히 저장됩니다.
좋아 해결했습니다.
GitHub에 솔루션 추가-http : //gregorypratt.github.com/AngularDynamicRouting
내 app.js 라우팅 구성에서 :
$routeProvider.when('/pages/:name', {
templateUrl: '/pages/home.html',
controller: CMSController
});
그런 다음 내 CMS 컨트롤러에서 :
function CMSController($scope, $route, $routeParams) {
$route.current.templateUrl = '/pages/' + $routeParams.name + ".html";
$.get($route.current.templateUrl, function (data) {
$scope.$apply(function () {
$('#views').html($compile(data)($scope));
});
});
...
}
CMSController.$inject = ['$scope', '$route', '$routeParams'];
#views가 내 <div id="views" ng-view></div>
이제 표준 라우팅 및 동적 라우팅과 함께 작동합니다.
그것을 테스트하기 위해 나는 그것을 Portfolio.html이라고 부르는 about.html을 복사하고 그것의 내용 중 일부를 변경 /#/pages/portfolio
하고 내 브라우저에 입력 했고 hey presto Portfolio.html이 표시되었습니다 ....
업데이트 추가 $을 적용하고 동적 인 내용 때문에 HTML로 $ 컴파일 주입 할 수있다.
그런 일을하는 가장 쉬운 방법은 나중에 경로를 해결하는 것이라고 생각합니다. 예를 들어 json을 통해 경로를 요청할 수 있습니다. 구성 단계에서 $ provide를 통해 $ routeProvider에서 팩토리를 만들어 실행 단계와 컨트롤러에서도 $ routeProvider 개체를 계속 사용할 수 있는지 확인합니다.
'use strict';
angular.module('myapp', []).config(function($provide, $routeProvider) {
$provide.factory('$routeProvider', function () {
return $routeProvider;
});
}).run(function($routeProvider, $http) {
$routeProvider.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
}).otherwise({
redirectTo: '/'
});
$http.get('/dynamic-routes.json').success(function(data) {
$routeProvider.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
});
// you might need to call $route.reload() if the route changed
$route.reload();
});
});
In the $routeProvider URI patters, you can specify variable parameters, like so: $routeProvider.when('/page/:pageNumber' ...
, and access it in your controller via $routeParams.
There is a good example at the end of the $route page: http://docs.angularjs.org/api/ng.$route
EDIT (for the edited question):
The routing system is unfortunately very limited - there is a lot of discussion on this topic, and some solutions have been proposed, namely via creating multiple named views, etc.. But right now, the ngView directive serves only ONE view per route, on a one-to-one basis. You can go about this in multiple ways - the simpler one would be to use the view's template as a loader, with a <ng-include src="myTemplateUrl"></ng-include>
tag in it ($scope.myTemplateUrl would be created in the controller).
I use a more complex (but cleaner, for larger and more complicated problems) solution, basically skipping the $route service altogether, that is detailed here:
Not sure why this works but dynamic (or wildcard if you prefer) routes are possible in angular 1.2.0-rc.2...
http://code.angularjs.org/1.2.0-rc.2/angular.min.js
http://code.angularjs.org/1.2.0-rc.2/angular-route.min.js
angular.module('yadda', [
'ngRoute'
]).
config(function ($routeProvider, $locationProvider) {
$routeProvider.
when('/:a', {
template: '<div ng-include="templateUrl">Loading...</div>',
controller: 'DynamicController'
}).
controller('DynamicController', function ($scope, $routeParams) {
console.log($routeParams);
$scope.templateUrl = 'partials/' + $routeParams.a;
}).
example.com/foo -> loads "foo" partial
example.com/bar-> loads "bar" partial
No need for any adjustments in the ng-view. The '/:a' case is the only variable I have found that will acheive this.. '/:foo' does not work unless your partials are all foo1, foo2, etc... '/:a' works with any partial name.
All values fire the dynamic controller - so there is no "otherwise" but, I think it is what you're looking for in a dynamic or wildcard routing scenario..
As of AngularJS 1.1.3, you can now do exactly what you want using the new catch-all parameter.
https://github.com/angular/angular.js/commit/7eafbb98c64c0dc079d7d3ec589f1270b7f6fea5
From the commit:
This allows routeProvider to accept parameters that matches substrings even when they contain slashes if they are prefixed with an asterisk instead of a colon. For example, routes like
edit/color/:color/largecode/*largecode
will match with something like thishttp://appdomain.com/edit/color/brown/largecode/code/with/slashs
.
I have tested it out myself (using 1.1.5) and it works great. Just keep in mind that each new URL will reload your controller, so to keep any kind of state, you may need to use a custom service.
Here is another solution that works good.
(function() {
'use strict';
angular.module('cms').config(route);
route.$inject = ['$routeProvider'];
function route($routeProvider) {
$routeProvider
.when('/:section', {
templateUrl: buildPath
})
.when('/:section/:page', {
templateUrl: buildPath
})
.when('/:section/:page/:task', {
templateUrl: buildPath
});
}
function buildPath(path) {
var layout = 'layout';
angular.forEach(path, function(value) {
value = value.charAt(0).toUpperCase() + value.substring(1);
layout += value;
});
layout += '.tpl';
return 'client/app/layouts/' + layout;
}
})();
참고URL : https://stackoverflow.com/questions/13681116/angularjs-dynamic-routing
'developer tip' 카테고리의 다른 글
시간을 사용하지 않고 모든 고 루틴이 끝날 때까지 기다리는 방법. (0) | 2020.09.09 |
---|---|
방정식에서 중괄호 옆에있는 두 개의 문 (0) | 2020.09.09 |
빈 문자열을 무시하는 String.Join 메서드? (0) | 2020.09.09 |
Xcode 6/7/8에서 디버그 빌드와 릴리스 빌드간에 어떻게 전환합니까? (0) | 2020.09.09 |
DOM 노드의 문자열 표현 가져 오기 (0) | 2020.09.09 |