更改 $scope.$on 函数中的 $scope.variable 不会更新视图

One*_*one 5 angularjs angularjs-scope angular-ui-router

我想监听路线更改并更新 $scope 变量以反映菜单中的当前路线(md-nav-bar):

$scope.$on('$routeChangeSuccess', function(event, current) {
    $scope.currentNavItem = $location.path();
    console.log('current location path', $scope.currentNavItem);
});
Run Code Online (Sandbox Code Playgroud)

输出是正确的(例如“/overview”),但是视图/菜单未更新。我需要手动启动更新吗?

gyc*_*gyc 5

如果您更改事件函数中的作用域变量(setTimeOut、$scope.$on...等),则必须手动调用$scope.$apply()要在作用域中更新的变量。

$scope.$on('$routeChangeSuccess', function(event, current) {
    $scope.currentNavItem = $location.path();
    $scope.$apply();
});
Run Code Online (Sandbox Code Playgroud)

如果这以某种方式导致错误“摘要已在进行中”,您可以在设置变量的代码周围包装一个超时函数:

$scope.$on('$routeChangeSuccess', function(event, current) {
  $timeout(function() {
    $scope.currentNavItem = $location.path();
  })
}
Run Code Online (Sandbox Code Playgroud)

但是,scope/rootScope 事件不应用于次要变量更新。它不可扩展,最终您将得到大量的事件侦听器。

在这种特殊情况下,您应该使用 ui-router 中可用的工具:

  • 用户界面参考
  • ui-sref-活动

您可能已经使用过ui-sref在状态之间导航:

<a ui-sref="state1">state1</a>
<a ui-sref="state2">state2</a>
Run Code Online (Sandbox Code Playgroud)

通过 ui-router,您还可以使用ui-sref-active指令将类添加到您的链接(如果状态对应)。

<a ui-sref="state1" ui-sref-active="active">state1</a>
<a ui-sref="state2" ui-sref-active="active">state2</a>
Run Code Online (Sandbox Code Playgroud)

当点击 state1 时,会生成以下 html:

<a ui-sref="state1" ui-sref-active="active" class="active">state1</a>
<a ui-sref="state2" ui-sref-active="active" class="">state2</a>
Run Code Online (Sandbox Code Playgroud)

然后,您可以随意设置活动类的样式。