code

AngularJS-templateUrl을 생성 할 때 $ routeParams를 사용하는 방법은 무엇입니까?

codestyles 2020. 8. 26. 07:54
반응형

AngularJS-templateUrl을 생성 할 때 $ routeParams를 사용하는 방법은 무엇입니까?


우리 응용 프로그램에는 2 단계 탐색 기능이 있습니다. AngularJS를 사용 $routeProvider하여 <ng-view />. 나는 이것에 따라 무언가를 할 생각을하고 있었다.

angular.module('myApp', []).
config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/:primaryNav/:secondaryNav', {
        templateUrl: 'resources/angular/templates/nav/'+<<primaryNavHere>>+'/'+<<secondaryNavHere>>+'.html'
    });
}]);

내에서 부품을 채우는 방법을 모르겠습니다 <<>>. primaryNav 및 secondaryNav가 $ routeParams에 바인딩된다는 것을 알고 있지만 템플릿을 동적으로 제공하기 위해 여기서 $ routeParams에 어떻게 액세스합니까?


나는 $routeParams서비스 를 주입하고 사용하는 방법을 찾을 수 없었습니다 (더 나은 해결책이 될 것이라고 생각합니다) 나는 이것이 효과가 있다고 생각했습니다.

angular.module('myApp', []).
    config(function ($routeProvider, $routeParams) {
        $routeProvider.when('/:primaryNav/:secondaryNav', {
            templateUrl: 'resources/angular/templates/nav/'+$routeParams.primaryNav+'/'+$routeParams.secondaryNav+'.html'
        });
    });

이 오류가 발생했습니다.

알 수없는 공급자 : myApp의 $ routeParams

이와 같은 것이 가능하지 않은 경우 다음과 같이 s를 사용하여 컨트롤러에서 URL을 설정 templateUrl하는 부분 HTML 파일을 가리 키도록 변경할 수 있습니다 .ng-include$routeParam

angular.module('myApp', []).
    config(function ($routeProvider) {
        $routeProvider.when('/:primaryNav/:secondaryNav', {
            templateUrl: 'resources/angular/templates/nav/urlRouter.html',
            controller: 'RouteController'
        });
    });

function RouteController($scope, $routeParams) {
        $scope.templateUrl = 'resources/angular/templates/nav/'+$routeParams.primaryNav+'/'+$routeParams.secondaryNav+'.html';
    }

이것으로 당신의 urlRouter.html

<div ng-include src="templateUrl"></div>

이 매우 유용한 기능은 이제 AngularJS 버전 1.1.2부터 사용할 수 있습니다. 불안정한 것으로 간주되지만 (1.1.3) 사용했으며 잘 작동합니다.

기본적으로 함수를 사용하여 templateUrl 문자열을 생성 할 수 있습니다. 이 함수에는 templateUrl 문자열을 빌드하고 반환하는 데 사용할 수있는 경로 매개 변수가 전달됩니다.

var app = angular.module('app',[]);

app.config(
    function($routeProvider) {
        $routeProvider.
            when('/', {templateUrl:'/home'}).
            when('/users/:user_id', 
                {   
                    controller:UserView, 
                    templateUrl: function(params){ return '/users/view/' + params.user_id; }
                }
            ).
            otherwise({redirectTo:'/'});
    }
);

풀 요청에 대해 https://github.com/lrlopez 에게 감사드립니다 .

https://github.com/angular/angular.js/pull/1524


templateUrl은 생성 된 URL을 반환하는 함수로 사용할 수 있습니다. routeParams를받는 인수를 전달하여 URL을 조작 할 수 있습니다.

예를 참조하십시오.

.when('/:screenName/list',{
    templateUrl: function(params){
         return params.screenName +'/listUI'
    }
})

Hope this help.


Alright, think I got it...

Little background first: The reason I needed this was to stick Angular on top of Node Express and have Jade process my partials for me.

So here's whatchya gotta do... (drink beer and spend 20+ hours on it first!!!)...

When you set up your module, save the $routeProvider globally:

// app.js:
var routeProvider
    , app = angular.module('Isomorph', ['ngResource']).config(function($routeProvider){

        routeProvider = $routeProvider;
        $routeProvider
            .when('/', {templateUrl: '/login', controller: 'AppCtrl'})
            .when('/home', {templateUrl: '/', controller: 'AppCtrl'})
            .when('/login', {templateUrl: '/login', controller: 'AppCtrl'})
            .when('/SAMPLE', {templateUrl: '/SAMPLE', controller: 'SAMPLECtrl'})
            .when('/map', {templateUrl: '/map', controller: 'MapCtrl'})
            .when('/chat', {templateUrl: '/chat', controller: 'ChatCtrl'})
            .when('/blog', {templateUrl: '/blog', controller: 'BlogCtrl'})
            .when('/files', {templateUrl: '/files', controller: 'FilesCtrl'})
            .when('/tasks', {templateUrl: '/tasks', controller: 'TasksCtrl'})
            .when('/tasks/new', {templateUrl: '/tasks/new', controller: 'NewTaskCtrl'})
            .when('/tasks/:id', {templateUrl: '/tasks', controller: 'ViewTaskCtrl'})
            .when('/tasks/:id/edit', {templateUrl: '/tasks', controller: 'EditTaskCtrl'})
            .when('/tasks/:id/delete', {templateUrl: '/tasks', controller: 'DeleteTaskCtrl'})
        .otherwise({redirectTo: '/login'});

});

// ctrls.js
...
app.controller('EditTaskCtrl', function($scope, $routeParams, $location, $http){

    var idParam = $routeParams.id;
    routeProvider.when('/tasks/:id/edit/', {templateUrl: '/tasks/' + idParam + '/edit'});
    $location.path('/tasks/' + idParam + '/edit/');

});
...

That may be more info than what was needed...

  • Basically, you'll wanna store your Module's $routeProvider var globally, eg as routeProvider so that it can be accessed by your Controllers.

  • Then you can just use routeProvider and create a NEW route (you can't 'RESET a route' / 'REpromise'; you must create a new one), I just added a slash (/) at the end so that it is as semantic as the first.

  • Then (inside your Controller), set the templateUrl to the view you want to hit.

  • Take out the controller property of the .when() object, lest you get an infinite request loop.

  • And finally (still inside the Controller), use $location.path() to redirect to the route that was just created.

If you're interested in how to slap an Angular app onto an Express app, you can fork my repo here: https://github.com/cScarlson/isomorph.

And this method also allows for you to keep the AngularJS Bidirectional Data-Bindings in case you want to bind your HTML to your database using WebSockets: otherwise without this method, your Angular data-bindings will just output {{model.param}}.

If you clone this at this time, you'll need mongoDB on your machine to run it.

Hope this solves this issue!

Cody

Don't drink your bathwater.


Router:-

...
.when('/enquiry/:page', {
    template: '<div ng-include src="templateUrl" onload="onLoad()"></div>',
    controller: 'enquiryCtrl'
})
...

Controller:-

...
// template onload event
$scope.onLoad = function() {
    console.log('onLoad()');
    f_tcalInit();  // or other onload stuff
}

// initialize
$scope.templateUrl = 'ci_index.php/adminctrl/enquiry/'+$routeParams.page;
...

I believe it is a weakness in angularjs that $routeParams is NOT visible inside the router. A tiny enhancement would make a world of difference during implementation.


I've added support for this in my fork of angular. It allows you to specify

$routeProvider
    .when('/:some/:param/:filled/:url', {
          templateUrl:'/:some/:param/:filled/template.ng.html'
     });

https://github.com/jamie-pate/angular.js/commit/dc9be174af2f6e8d55b798209dfb9235f390b934

not sure this will get picked up as it is kind of against the grain for angular, but it is useful to me


//module dependent on ngRoute  
 var app=angular.module("myApp",['ngRoute']);
    //spa-Route Config file
    app.config(function($routeProvider,$locationProvider){
          $locationProvider.hashPrefix('');
          $routeProvider
            .when('/',{template:'HOME'})
            .when('/about/:paramOne/:paramTwo',{template:'ABOUT',controller:'aboutCtrl'})
            .otherwise({template:'Not Found'});
    }
   //aboutUs controller 
    app.controller('aboutCtrl',function($routeParams){
          $scope.paramOnePrint=$routeParams.paramOne;
          $scope.paramTwoPrint=$routeParams.paramTwo;
    });

in index.html

<a ng-href="#/about/firstParam/secondParam">About</a>

firstParam and secondParam can be anything according to your needs.


I was having a similar issue and used $stateParams instead of routeParam

참고URL : https://stackoverflow.com/questions/11534710/angularjs-how-to-use-routeparams-in-generating-the-templateurl

반응형