【问题标题】:AngularJS - Update controller var on route changeAngularJS - 在路由更改时更新控制器变量
【发布时间】:2017-05-22 07:59:20
【问题描述】:

我几乎是 AngularJS 世界的新手。 这是我的问题。我想根据 url 更新选中的标签,这样选中的标签会随着 url 的变化而变化。

这是我的 js:

app.config(function($routeProvider, $locationProvider){
      $routeProvider
        .when('/page1', {
          templateUrl: '/views/pages/page1.html',
          controller: "TabController",
          tab: 1
        })
         .when('/page2', {
          templateUrl: '/views/pages/page2.html',
          controller: "TabController",
          tab: 2
        })
        .otherwise({
          template: "Error 404"
        });

        $locationProvider.html5Mode({enabled: true, requireBase: false});
    });

    //Tabs
    app.controller("TabController", function($scope, $route){
      $scope.activeTab = 0;

      if(typeof $route.current != "undefined"){
        setTimeout(function(){$scope.activeTab = $route.current.activeTab; console.log($scope.activeTab);},100);
      }
    });

这是我的html:

<div ng-controller="TabController">
  <!-- Tabs -->
  <section class="section section--xs">
    <div class="container">
      <div class="tab">
        <div class="tab__single" ng-class="{active: activeTab === 1}">
          <a href="/page1" class="tab__single__name">Page 1</a>
        </div>
        <div class="tab__single" ng-class="{active: activeTab === 2}">
          <a href="/page2" class="tab__single__name">Page 2</a>
        </div>
      </div>
    </div>
  </section>
  <!-- ./tabs -->

  <!-- Content -->
  <ng-view></ng-view>
  <!-- ./content -->
</div>

我尝试,如果我记录选项卡值,它实际上会更新,因为它记录了正确的值,但是新选项卡没有被选中。有什么建议吗?

【问题讨论】:

  • 这可能是help
  • @ricky 我尝试了第一个解决方案,但它仍然没有更新!

标签: javascript angularjs angularjs-directive angularjs-scope angular-routing


【解决方案1】:

您可以创建一个函数来搜索您的 url 参数:

$scope.isActive = function (viewLocation) { 
    return viewLocation === $location.path();
};

HTML:

<div class="tab">
        <div class="tab__single" ng-class="{active: isActive('page1')}">
          <a href="/page1" class="tab__single__name">Page 1</a>
        </div>
        <div class="tab__single" ng-class="{active: isActive('page2')}">
          <a href="/page2" class="tab__single__name">Page 2</a>
        </div>
      </div>

【讨论】:

  • 非常感谢!这似乎工作得很好!
猜你喜欢
  • 2015-03-07
  • 2015-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多