【问题标题】:set current tab as active tab using Angularjs使用Angularjs将当前选项卡设置为活动选项卡
【发布时间】:2018-01-03 10:54:14
【问题描述】:

我设置了五个选项卡,它们工作正常。当我刷新页面时,当前活动的选项卡将转移到默认状态。 但是我想将它设置为当前的活动状态,即使在我刷新之后也是如此。请让我知道我哪里出错了

HTML代码:

    <div class="container">
    <section ng-app="myApp" ng-controller="TabController as tab">
       <ul class="nav nav-pills">
            <li ng-class="{active:tab.isSet(1)}"><a href ng-click="tab.setTab(1)">Home</a></li>
            <li ng-class="{active:tab.isSet(2)}"><a href ng-click="tab.setTab(2)">Underwriting</a></li>
            <li ng-class="{active:tab.isSet(3)}"><a href ng-click="tab.setTab(3)">Operations</a></li>
        </ul>

        <div ng-show="tab.isSet(1)">
             <h4>Home</h4>
        </div>
        <div ng-show="tab.isSet(2)">
             <h4>Underwriting</h4>
        </div>
        <div ng-show="tab.isSet(3)">
             <h4>Operations</h4>
        </div>
    </section>
</div>

Js:

    (function () {
    var app = angular.module('myApp', []);

    app.controller('TabController', function () {
        this.tab = 1;  ---> Here I am failing to apply the logic.

        this.setTab = function (tabId) {
            this.tab = tabId;
        };

        this.isSet = function (tabId) {
            return this.tab === tabId;
        };
    });
})();

工作演示:http://jsfiddle.net/fwoxdjsu/

【问题讨论】:

  • 您需要将活动标签存储在某处(如本地存储/服务器)。在页面刷新时读取标签数据并设置它。
  • 使用网络存储 developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API 并检查存储是否之前设置了值
  • localstorage 正在工作,但这是不好的方式。为此,您可以使用角度路由器或 ui-router

标签: javascript angularjs


【解决方案1】:

将标签索引存储在本地存储中,并在页面刷新时再次设置它。由于索引来自本地存储的字符串转换为数字。

this.tab = +localStorage.getItem('tabIndex') || 1;
this.setTab = function (tabId) {
  this.tab = tabId;
  localStorage.setItem('tabIndex', tabId);
};

这里是jsFiddle

【讨论】:

    【解决方案2】:

    更新Js

    (function () {
        var app = angular.module('myApp', []);
    
        app.controller('TabController', function () {
            if(typeof(localStorage.currentTab)=="undefined")
                this.tab = 1;
            else 
                this.tab = parseInt(localStorage.currentTab);
    
            this.setTab = function (tabId) {
                    localStorage.currentTab=tabId;
                this.tab = tabId;
            };
            this.isSet = function (tabId) {
                return this.tab === tabId;
            };
        });
    })();
    

    【讨论】:

      猜你喜欢
      • 2019-05-17
      • 1970-01-01
      • 1970-01-01
      • 2013-07-24
      • 2023-03-22
      • 2017-01-09
      • 1970-01-01
      • 1970-01-01
      • 2014-09-12
      相关资源
      最近更新 更多