使用来自不同控制器的$ location.path()来显示导航按钮:AngularJS

时间:2015-12-01 12:30:23

标签: angularjs angular-services ng-show ng-hide

这是前两个问题的延伸; How do I use angular ng-hide based on the page/route that I am currently on?How can I use ng-hide if $location.url == base (root) url?两者都涉及使用$location.path()显示导航项,具体取决于当前路线。

我有一个非常简单的联系人列表样式的SPA,只有页眉,页脚和各种视图。标题有3个导航按钮。每个都使用绑定到ng-click的函数来更改路径,并使用布尔测试进行显示,例如

<button ng-click="changePath('/summary')" ng-hide="path == '/summary' ">Summary</button>

在附加的 HeaderController 中,注入了$location服务,我们有。

var vm = this;
vm.path = $location.path();
vm.changePath = changePath;

function changePath (newPath) {
    this.path = newPath;
    $location.path(newPath);
}

除了两个实例外,这一切都按预期工作。

首先,当应用程序首次加载时。默认路由配置设置为.otherwise({redirectTo : "/summary"},但仍会显示摘要按钮。

其次,当使用不同的控制器从页面视图内部更改路径时。例如,在摘要页面中,每个联系人都有一个链接,该链接将加载包含所有详细信息的新页面。

<div ng-repeat="data in contacts">
    ...
    <span ng-click="showDetails(contacts.indexOf(data))">Info</span>
</div>

和关联的 SummaryController 再次使用$location来更改路径

var vm = this;
vm.contacts = dataStore.getDetails();
vm.showDetails = showDetails;

function showDetails(index) {
    $location.path("/details/" + index);
}

和以前一样,这可以按预期工作;将显示包含相应详细信息的视图,但不会更新导航按钮。

在这两种情况下,简单的浏览器页面刷新都会显示正确的导航按钮。

我的理解是$location应广播路线更改https://stackoverflow.com/a/12429133/2980217。但是,页面刷新表明可能需要通过调用$digest来触发$apply周期,但这似乎错误

我已根据此回复https://stackoverflow.com/a/24144088/2980217尝试在$location.path()内包裹$timeout,但这样做无效。

12月2日编辑:我已将该应用的骨架版本设为plu http://plnkr.co/edit/7bQn6G9HveHajBMdrDfR

对于应用加载问题,似乎模板首先加载$location.path()为空字符串。为了解决这个问题,我使用了一个简单的条件来手动设置currentPath变量。

我看起来需要的是页面刷新。根据这篇文章https://www.sitepoint.com/premium/books/angularjs-novice-to-ninja/preview/exploring-the-location-service-2f17ca5使用$window.location.href是可行的方法。我已经给了它一个但没有成功。

也许我会以错误的方式解决这个问题。任何建议都将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:0)

答案在这里:https://stackoverflow.com/a/24831979/2980217

非常简单:使用自定义服务来处理路径的所有更改。

  • Angular的$ location服务可以注入此服务。
  • 将此服务注入到路径更改的每个控制器中。
  • 新服务使用$ rootScope广播更改。 $rootScope.$broadcast("pathChanged", newPath);
  • 导航按钮的控制器侦听广播,并相应地更新当前路径的模型。这会触发视图(即导航按钮)根据需要显示或隐藏。

    $scope.$on("pathChanged", updatePath)
    
    function updatePath(evt, updatedPath) {
       vm.currentPath = updatedPath;
    }
    

更新的Plunk在这里:http://plnkr.co/edit/7bQn6G9HveHajBMdrDfR