2016-10-11 4 views
0

를 컨트롤러에 변수를 전달 내가 컨트롤러에 매개 변수를 보낼 필요가AngularJS와 -

function config($routeProvider, $locationProvider) { 

    $routeProvider 

     .when('/url-1', { 
      parameter: 1 
     }) 

     .when('/url-2', { 
      parameter: 2 
     }) 

     .otherwise({ 
      redirectTo: '/url-1' 
     }); 

    $locationProvider.html5Mode({ 
     enabled: true, 
     requireBase: true 
    }); 
} 

이 내 컨트롤러

function MyController(parameter) { 

    console.log(parameter); 

} 

이며보기에 난 단지 두 개의 링크

<a ng-href="/url-1">url-1</a> 
<a ng-href="/url-2">url-1</a> 

컨트롤러를 $ routeProvider에 지정해야합니까? 컨트롤러가 하나뿐입니다. 나는 dinamically 의견을로드하지 않습니다 난 그냥 $ routeProvider 보낸 매개 변수를 기반으로 console.log (매개 변수) 할 필요가

감사합니다!

답변

0

이것은 당신이 다음 완패 정의는 그 번호로 증가 얻을 것이다 (100 개) 경로가있는 경우 가정, 경로를 정의하는 좋은 방법이 될 것입니다. 여러 경로에는 단일 일반 경로가 있습니다.

그리고 당신은 경로에서 매개 변수를 사용할 얻을 $ routeParams API에 액세스 할 수있는 노선 컨트롤러를 지정합니다.

구성

function config($routeProvider, $locationProvider) { 

    $routeProvider 
    .when('/url/:id', { 
     controller: MyController 
    }) 
    .otherwise({ 
     redirectTo: '/url/1' 
    }); 

    $locationProvider.html5Mode({ 
     enabled: true, 
     requireBase: true 
    }); 
} 

컨트롤러

function MyController($routeParams) { 
    console.log($routeParams); 
} 

당신은 다음 routeChangeSuccess 이벤트에 후크를 배치하여 노선 변경을 추적 할 수 있습니다 각 경로에 대한 또 다른 컨트롤러를 배치하지 않으려면 응용 프로그램의 내부 실행 블록은 아래와 같습니다.

app.run(function($rootScope, $routeParams) { 
    $rootScope.$on('routeChangeSuccess', function() { 
     console.log($routeParams); 
    } 
}); 

또는 본문에있는 페이지 컨트롤러 내에 해당 이벤트를 가질 수 있습니다.

function MyController($scope, $routeParams) { 
    console.log("Parameters on page load "+ $routeParams); 
    $scope.$on('$routeChangeSuccess', function(event, next, current) { 
     console.log($routeParams); 
    } 
} 
+0

}

function MyController($routeParams) { console.log($routeParams); 

} controller = "MyController as vm"> – handsome

+0

더 확장 성이 있다고 제안한 접근 방식을 따르십시오. 이제 라우트 당 컨트롤러를 할당하고 싶지 않다면,'$ routeChangeSuccess' 이벤트에 후크 할 수 있습니다. –

+0

정말 감사드립니다. 내가 모든 URL이 동일하고 (그리고 오직) 가고 있기 때문에 라우트 당 컨트롤러를 할당해야하는 이유는 분명하지 않다. 내가보기에서 컨트롤러를 호출하고있다. $ routeProvider에서 동일한 작업을 수행하면 어떻게됩니까? – handsome

0
function config($routeProvider, $locationProvider) { 

$routeProvider 

    .when('/url-1', { 
     params: {id : 1} 
    }) 

    .when('/url-2', { 
     params: {id : 2} 
    }) 

    .otherwise({ 
     redirectTo: '/url-1' 
    }); 

$locationProvider.html5Mode({ 
    enabled: true, 
    requireBase: true 
}); 

난 단지 2 개 경로를 가지고

+0

링크를 클릭하면 변경 사항이 표시되지 않습니다. :( – handsome