2012-07-19 4 views
11

이것은 기본적으로이 질문의 후속 질문입니다 : AngularJS - How to use $routeParams in generating the templateUrl?. 이 질문의 적절한 컨텍스트에 대한 내 코드를 참조하십시오.AngularJS - URL을 기반으로 한 업데이트 모델

모든 탐색 부분이 훌륭하게 작동하지만 지금은 탐색 할 때 primaryNavsecondaryNav을 기반으로 내 $scope의 일부 속성을 업데이트하려고합니다. 내가 $watch으로 뭔가를 할 수있을 거라 생각했지만 아무 것도 할 수없는 것처럼 보입니다. 아마이 NAVS을 가지고 모든 것을 업데이트하고 떨어져 이동하고 단지 모든 앵커 태그에 ng-click를 추가 내 컨트롤러에 몇 가지 방법을 만들 수

$scope.$watch($location.path(), function() {...}); //result in js error 
$scope.$watch($location, function() {...}); //function runs once on page load, but not after that 
$scope.$watch($window.location, function() {...}); //function runs once on page load, but not after that 
$scope.$watch(window.location, function() {...}); //function runs once on page load, but not after that 
$scope.$watch(window.location.href, function() {...}); //results in js error 

: 여기에 내가 시도 몇 가지 있습니다. 그러나 AngularJS에 대해 정말 좋아하는 한 가지는 hrefs에 대한 실제 URL 조회 값 (예 : <a href="#/priNav/secNav">Foo</a>)을 사용하는 것이 었습니다. 컨트롤러에서 어떤 방법을 거치지 않고 라우팅 할 때 URL 변경에 따라 모델을 업데이트 할 수 있습니까? 내가 바라는 것이 그것이 의미가 있기를 바랍니다.

답변

33
$scope.$watch(function() { 
    return $location.path(); 
}, function(){ 
    ... 
}); 

당신은 기능이나

+0

아 ... 난 함수를보고 잊어 범위 내에서 평가 될 수있는 문자열을 전달해야한다. 노력하고있는 모든 것은 끈에 달려있었습니다. $ scope. $ watch ($ location.path, function() {});은 작동하지 않지만'$ scope. $ watch (function() {return $ location.path()}, function() { ...}); '않습니다. 고맙습니다! – dnc253

+2

고마워요! [$ location.search] (http://sharepointkunskap.wordpress.com/2012/11/22/angularjs-sync-location-search-with-an-input-value/)에서도 작동합니다. –

관련 문제