AngularJS - 基于URL的更新模型

dnc*_*253 11 javascript angularjs

这基本上是一个跟进问题这个问题:AngularJS - 如何使用$ routeParams生成templateUrl?.请查看我的代码,了解此问题的正确背景.

所有导航部分都运行良好,但现在当我导航时,我想$scope基于primaryNav和更新我的一些属性secondaryNav.我以为我可以做些什么,$watch但我似乎无法得到任何工作.以下是我尝试过的一些事情:

$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
Run Code Online (Sandbox Code Playgroud)

我可以在我的控制器中创建一些方法来获取这些导航并更新所有内容并导航,然后只添加一个ng-click到所有锚标签.然而,我真正喜欢AngularJS的一件事是为hrefs使用真实的URL值(例如<a href="#/priNav/secNav">Foo</a>).当我在没有经过控制器上的某些方法的情况下路由时,是否无法根据更改的URL更新我的模型?我希望我的要求是有道理的.

Ren*_*des 33

 $scope.$watch(function() {
    return $location.path();
 }, function(){
    ...
 });
Run Code Online (Sandbox Code Playgroud)

你应该传递一个可以在范围内进行评估的函数或字符串

  • 谢谢!它甚至适用于[$ location.search](http://sharepointkunskap.wordpress.com/2012/11/22/angularjs-sync-location-search-with-an-input-value/) (2认同)