2014-10-28 2 views
0

내 경로 파일 내 HEADER.html 현재의 파셜에서각도 경로를 사용하여 현재 상태에서 활성 클래스를 설정하는 방법은 무엇입니까?

app.config(["$routeProvider",function($route) 
{ 
    $route.when("/",{ 
     templateUrl : "partials/index.html", 
     controller : "AppCtrl" 
    }).when("/contact",{ 
     templateUrl:"partials/contact.html", 
     controller:"ContactCtrl" 
    }). 
    when("/about-us",{ 
     templateUrl:"partials/about.html", 
     controller:"AboutCtrl" 
    }). 
    when("/gallery",{ 
     templateUrl:"partials/gallery.html", 
     controller:"GalleryCtrl" 
    }). 
    otherwise({ 
     redirectTo:"/" 
    }); 

}]); 

을 내가 HeaderCtrl 컨트롤러를 사용하고

app.controller("HeaderCtrl",["$scope","$location",function($scope,$location) 
{ 
    $scope.location=$location.path().replace("/",""); 
}]); 

내 HEADER.html 현재

<ul ng-controller="HeaderCtrl"> 
    <li ng-class="{active:location===''}"><a href="#">home</a></li> 
    <li ng-class="{active:location==='about-us'}"><a href="#/about-us">about us</a></li> 
    <li ng-class="{active:location==='gallery'}"><a href="#/gallery">gallery</a></li> 
    <li ng-class="{active:location==='contact'}"><a href="#/contact">contact</a></li> 
</ul> 

때 페이지를 다시로드 (실제 새로 고침) 그럼 그것은 작동 클래스 즉, 각각의 리튬에 적용됩니다하지만 내가 (메뉴 항목을 클릭하여) 경로를 변경하면 작동하지 않습니다

+0

라우트가 변경 될 때 컨트롤러에서'$ scope.location'을 변경하지 않았기 때문입니다. – Brett

+0

그래, 나는 그것이 사실이라고 생각한다. 어떻게 극복 할 수 있을까? – ahhmarr

답변

2

문제의 해결책은 URL이 성공적으로 변경되면 $scope.location을 업데이트하는 이벤트를 바인딩하는 것입니다. 각 <li> 요소에 클릭 이벤트를 바인딩 할 필요가 없습니다. 경로가 잘못되었거나 실패하면 어떻게해야합니까? 요소가 실제 경로가 아니라면 활성 경로임을 사용자에게 보여주고 싶지는 않습니다.

$location 서비스의 documentation을 읽으면 이벤트 섹션이 표시됩니다. 우리가 관심을 가지는 것은 $locationChangeSuccess입니다. 컨트롤러에 연결하려면 다음을 수행하십시오 :

$scope.$on('$locationChangeSuccess', function() { 
    $scope.location = $location.path().replace('/', ''); 
}); 
+0

app.controller ("HeaderCtrl", "$ scope", "$ locationChangeSuccess", function ($ scope, $ location, $ locationChangeSuccess) { \t $ scope. $ on ('$ locationChangeSuccess' , function() { \t $ scope.location = $ location.path(). replace ('/', ''); \t}); }]); 이 코드에서 내가 실수 한 점은 무엇입니까? – ahhmarr

+0

'$ locationChangeSuccess'를 삽입 할 필요가 없습니다. 모듈이 아닙니다. '$ location' 서비스의 일부로 제공됩니다. 내가 게시 한 코드는 컨트롤러 기능에 필요한 모든 것입니다. – Brett

+0

매력처럼 일했습니다. 덕분에 너무 많이 :) – ahhmarr

관련 문제