【问题标题】:Changing the class in AngularJS using URL data使用 URL 数据更改 AngularJS 中的类
【发布时间】:2012-11-08 01:50:27
【问题描述】:

当我更改页面并使用 location.path() 或其他东西来获取相关的 URL 片段时,我想更改元素的类。

我正在使用 $routeProvider 进行路由。小提琴没有正确显示它,但它在我的代码中运行良好。我遇到的问题是当我加载下一页时它没有更新。

此代码获取我想要的 url 片段:

$scope.locationPath = $location.path().replace(/^\/([^\/]*).*$/, '$1');

这是一个非常简单的 JSfiddle: http://jsfiddle.net/timothybone/kmBXv/1/

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    will 的回答几乎是正确的;您必须将 $location.path() 包装在一个函数中,以便在每个摘要上执行它,而不仅仅是一次:

    $scope.$watch(function () {
      return $location.path();
    }, function() {
      return $location.path().replace(/^\/([^\/]*).*$/, '$1');
    });
    

    工作小提琴:http://jsfiddle.net/kmBXv/3/

    【讨论】:

      【解决方案2】:

      这样的事情怎么样?

      $scope.$watch($location.path(), function() {
        return $location.path().replace(/^\/([^\/]*).*$/, '$1');
      }
      

      【讨论】:

      • 我实现了这个逻辑,但是没有页面刷新它仍然不会更新。
      【解决方案3】:

      使用 $watch 的替代方法:

      <li ng-class="{active:isActiveRoute('edit')}">edit</li>
      <li ng-class="{active:isActiveRoute('list')}">list</li>
      

      然后在你的控制器中:

      $scope.isActiveRoute = function(route) {
         // I added '/' instead of using a regex to remove it from path()
         return '/' + route === $location.path();
      };
      

      另见AngularJs: stateful client-side routing,它有一个工作小提琴。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多