基于URL的更新模型

时间:2022-11-24 19:06:34

This is basically a follow up question this question: AngularJS - How to use $routeParams in generating the templateUrl?. See my code there for the proper context of this question.

这基本上是一个后续问题这个问题:AngularJS -如何使用$routeParams生成templateUrl?请查看我的代码,以获得这个问题的正确上下文。

All the navigation part is working great, but now when I navigate, I want to update some properties in my $scope based on the primaryNav and secondaryNav. I thought I could do something with $watch but I can't seem to get anything to work. Here are a few things I tried:

所有的导航部分都运行得很好,但是现在当我导航的时候,我想要基于primaryNav和secondaryNav更新我的$scope中的一些属性。我想我可以用$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

I could probably create some method in my controller that would take these navs and update everything and navigate off and just add a ng-click to all the anchor tags. However, one thing I really liked about AngularJS was being to use real URL-looking values for hrefs (e.g. <a href="#/priNav/secNav">Foo</a>). Is it not possible to update my model based on the changing URL when I route without going through some method on the controller? I hope it makes sense what I'm asking.

我可能可以在我的控制器中创建一些方法来获取这些navs并更新所有内容并导航,然后在所有锚标记中添加一个ng-click。然而,我非常喜欢AngularJS的一点是对hrefs使用真实的url查找值(例如Foo)。如果我不通过控制器上的一些方法来进行路由,难道不可能基于修改后的URL更新我的模型吗?我希望我说的有道理。

1 个解决方案

#1


33  

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

you should pass a function or a string that can be evaluated inside of the scope

您应该传递一个函数或字符串,该函数或字符串可以在范围内求值

#1


33  

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

you should pass a function or a string that can be evaluated inside of the scope

您应该传递一个函数或字符串,该函数或字符串可以在范围内求值