AngularJS和Bootstrap选项卡行为无法正常工作

时间:2016-04-10 23:05:22

标签: javascript angularjs twitter-bootstrap

所以这是我的观点代码:

<ul class="nav nav-pills" id="my-pill">
                <li class="active"><a href="#tab0" data-toggle="tab">Tools
                        Home</a></li>
                <li><a href="#tab1" data-toggle="tab">Fair Trade Judge</a></li>
                <li><a href="#tab2" data-toggle="tab">Awards</a></li>
                <li><a href="#tab3" data-toggle="tab">Draft Buddy</a></li>
                <li><a href="#tab4" data-toggle="tab">Add A League</a></li>
                <li><a href="#tab5" data-toggle="tab">Insult Generator</a></li>
                <li><a href="#tab6" data-toggle="tab">League Poll</a></li>
                <li><a href="#tab7" data-toggle="tab">Smart Rankings</a></li>
                <li><a href="#tab8" data-toggle="tab">Composite Rankings</a></li>
                <li><a href="#tab9" data-toggle="tab">Waiver Wire Pickup
                        Aid</a></li>
            </ul>
            <div class="tab-content">
                <div class="tab-pane active" id="tab0">
                    <div class="row">
                        <div class="col-md-12">
                            <h2>Tool Descriptions</h2>
                            <h3>Fair Trade Judge</h3>
                            <p>This tool will help you decide whether or not a proposed
                                trade is fair</p>
                            <h3>Awards</h3>
                            <p>Weekly awards given out to teams who have the best, and
                                worst weeks in the league</p>
                            <h3>Draft Buddy</h3>
                            <p>Use this tool to aid you during your big draft day</p>
                            <h3>Add A League</h3>
                            <p>This isn't really a tool, and doesn't fit on the
                                dashboard</p>
                            <h3>Insult Generator</h3>
                            <p>Let our team analysis algorithm pick apart any team in
                                your league with relevant insults</p>
                            <h3>League Poll</h3>
                            <p>Rank every team in your league on a weekly basis. Overall
                                rankings will be calculated based on the poll</p>
                            <h3>Smart Rankings</h3>
                            <p>This tool ranks every team in your league based on
                                complex rankings algorithm, that factors in more than just your
                                W-L-T record</p>
                            <h3>Composite Rankings</h3>
                            <p>Ever wonder what your record would be if you played every
                                team every week instead of the head to head match-up style?
                                This tool will tell you what your overall record would be</p>
                            <h3>Waiver Wire Pickup Aid</h3>
                            <p>See who our analysis of your team determines you should
                                pick up off of the waiver wire this week</p>
                        </div>
                    </div>
                </div>
                <div class="tab-pane" id="tab1" >
                    <h2>Select the teams that are going to do a trade, then
                        select the players</h2>
                    <div ng-controller="FTJController" class="teamWrapper">
                        <div class="col-md-6 team" style="float: left;">
                            {{list1}} <select ng-model="selectedTeam1"
                                ng-options="item as item.teamName for item in teams track by item.teamID"
                                ng-change="getRoster1(selectedTeam1)">
                                <option value="">Team 1</option>
                            </select>
                            <table class="table-striped" style="width: 100%">
                                <tr>
                                    <td></td>
                                    <td>Name</td>
                                    <td>Position</td>
                                    <td>NFLTeamName</td>
                                    <td>InjuryCode</td>
                                </tr>
                                <tr ng-repeat="player1 in roster1">
                                    <td><input type="radio" ng-value="{{player1.PlayerID}}"
                                        ng-model="selected1" ng-change="addID1(selected1)"
                                        name="selected1" /></td>
                                    <td>{{player1.Name}}</td>
                                    <td>{{player1.Position}}</td>
                                    <td>{{player1.NFLTeamName}}</td>
                                    <td>{{player1.InjuryCode}}</td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-offset-6 team">
                            {{list2}} <select ng-model="selectedTeam2"
                                ng-options="item as item.teamName for item in teams track by item.teamID"
                                ng-change="getRoster2(selectedTeam2)">
                                <option value="">Team 2</option>
                            </select>
                            <table class="table-striped" style="width: 100%">
                                <tr>
                                    <td></td>
                                    <td>Name</td>
                                    <td>Position</td>
                                    <td>NFLTeamName</td>
                                    <td>InjuryCode</td>
                                </tr>
                                <tr ng-repeat="player2 in roster2">
                                    <td><input type="radio" ng-value="{{player2.PlayerID}}"
                                        ng-model="selected2" ng-change="addID2(selected2)"
                                        name="selected2" /></td>
                                    <td>{{player2.Name}}</td>
                                    <td>{{player2.Position}}</td>
                                    <td>{{player2.NFLTeamName}}</td>
                                    <td>{{player2.InjuryCode}}</td>
                                </tr>
                            </table>
                        </div>
                        <br />
                        <div class="button">
                            <input type="button" value="compare players"
                                ng-click="comparePlayers()" />
                            <div>Is this trade fair? {{FTJ}}</div>
                        </div>
                    </div>
                </div>

每当我尝试单击其中一个选项卡,而不是加载数据时,它会将我重定向到我的登录页面。我不想要任何重定向,因为我需要在登录后加载所有数据。如果我将tab1的类更改为活动,我会得到我想要的数据行为,所以我认为这是Bootstrap的一个问题。有什么想法吗?

编辑:这是我的控制器文件(对API的调用工作正常)

HomeController.$inject = ['UserService', '$rootScope'];
function HomeController(UserService, $rootScope) {
var vm = this;

vm.user = null;
vm.allUsers = [];
vm.deleteUser = deleteUser;

initController();

function initController() {
    loadCurrentUser();

}

function loadCurrentUser() {
    UserService.GetByEmail($rootScope.globals.currentUser.email)
        .then(function (user) {
            vm.user = user.data;
        });
}

function deleteUser(id) {
    UserService.Delete(id)
    .then(function () {
        loadAllUsers();
    });
}
}

FTJController.$inject = ['$scope', '$http'];
function FTJController($scope, $http) {
$scope.list1 = 'Select Team 1';
$scope.list2 = 'Select Team 2';
//$scope.selectedTeam = null;
$scope.teams = [];
$scope.players1 = [];
$scope.players2 = [];
$scope.roster1 = null;
$scope.roster2 = null;
$http({
    method: 'GET',
    url: './rest/LeagueTeams?LeagueID=1682132'
}).success(function (result) {
    $scope.teams = result;
});
console.log("in controller");
$scope.getRoster1 = function(selectedTeam){
    console.log("in getRoster with teamID = " + selectedTeam.teamID);
    $http({
        method: 'GET',
        url: './rest/Roster?LeagueID=1682132&TeamID=' +selectedTeam.teamID + '&Week=1&Year=2015'
    }).then(function (result){
        $scope.roster1 = result.data;
    });

}
//duplicating for now, should change to use the same method for both rosters
$scope.getRoster2 = function(selectedTeam){
    console.log("in getRoster with teamID = " + selectedTeam.teamID);
    $http({
        method: 'GET',
        url: './rest/Roster?LeagueID=1682132&TeamID=' +selectedTeam.teamID + '&Week=1&Year=2015'
    }).then(function (result){
        $scope.roster2 = result.data;
    });
}

$scope.comparePlayers = function(){
    console.log("testingsss");
    console.log($scope.players1);
    console.log($scope.players2);
    console.log('call: ./rest/FTJ?PlayerID1=' + $scope.players1 + '&PlayerID2=' + $scope.players1);
    console.log('Is $scope.players1 ' + ($scope.players1) + ' > $scope.players2 ' + $scope.players1 + ' ?');
    console.log('comparison');
    console.log($scope.players1 > $scope.players2);
    $http({
        method: 'GET',
        url: './rest/FTJ?PlayerID1=' + $scope.players1 + '&PlayerID2=' + $scope.players2
    }).then(function (result){
        console.log('result.data');
        console.log(result.data);
        if (result.data){
            $scope.FTJ = "Hell yea";
        } else {
            $scope.FTJ = "f no";
        }
    });
};
$scope.addID1 = function(s){
    $scope.players1 = s;
    console.log($scope.players1);

};
$scope.addID2 = function(s){
    $scope.players2 = s;
    console.log($scope.players2);
};
}

这是我的app.js文件,其中包含路由:

(function () {
'use strict';

angular
    .module('app', ['ngRoute', 'ngCookies'])
    .config(config)
    .run(run);

config.$inject = ['$routeProvider', '$locationProvider'];
function config($routeProvider, $locationProvider) {
    $routeProvider
        .when('/', {
            controller: 'HomeController',
            templateUrl: 'home/home.view.html/',
            controllerAs: 'vm'
        })

        .when('/login', {
            controller: 'LoginController',
            templateUrl: 'login/login.view.html',
            controllerAs: 'vm'
        })

        .when('/register', {
            controller: 'RegisterController',
            templateUrl: 'register/register.view.html',
            controllerAs: 'vm'
        })

        .otherwise({ redirectTo: '/login' });
}

run.$inject = ['$rootScope', '$location', '$cookieStore', '$http'];
function run($rootScope, $location, $cookieStore, $http) {
    // keep user logged in after page refresh
    $rootScope.globals = $cookieStore.get('globals') || {};
    if ($rootScope.globals.currentUser) {
        $http.defaults.headers.common['Authorization'] = 'Basic ' +     $rootScope.globals.currentUser.authdata; // jshint ignore:line
    }

    $rootScope.$on('$locationChangeStart', function (event, next, current) {
        // redirect to login page if not logged in and trying to access a restricted page
        var restrictedPage = $.inArray($location.path(), ['/login', '/register']) === -1;
        var loggedIn = $rootScope.globals.currentUser;
        if (restrictedPage && !loggedIn) {
            $location.path('/login');
        }
    });
}
})();

如何修复路由,以便在单击tab1时,它只显示数据并移动到该选项卡而不是重定向到登录?谢谢!

8 个答案:

答案 0 :(得分:12)

这是因为角度路由... 您只需向每个锚标记添加以下属性即可 目标=&#34; _self&#34;

例如:<li><a href="#tab1" data-toggle="tab" target="_self">Fair Trade Judge</a></li>

希望它能解决它。

答案 1 :(得分:0)

当您单击链接时,Angular路由器将路由到#tab1。由于没有定义此类路由且登录屏幕是默认路由,因此必须显示登录屏幕。

你可以使用angular-ui轻松地使用角度来进行自举工作。

答案 2 :(得分:0)

您的默认页面,因为找不到已定义的路线。

所以,你可以做的是你可以处理标签点击事件并使用

来防止这种默认行为
e.preventDefault();

您有两种选择:

  1. 为每个标签添加ng-click="show($event)"

    例如,在控制器中

    $scope.show = function (e) {
        e.preventDefault();
        jQuery('.nav-pills[href="e.targrt.hash"]').tab('show')
    };
    

    检查Bootstrap文档以获取更多详细信息:http://getbootstrap.com/javascript/#tabs

  2. 或添加指令来处理事件。

    <a show-tab href="#tab0" data-toggle="tab">Tools Home</a>
    
    app.directive('showTab', function () {
    
    // here first prevent deault behaviour of a tab,  then add new click event which invokes jQuery related stuff for tabs
    return function (scope, iElement, iAttributes) {        
        iElement.click(function (e) {
            e.preventDefault();
            $(iElement).tab('show');
        });
    };
    

    这是更好的选择。

  3. 请检查此链接如何操作:https://www.grobmeier.de/bootstrap-tabs-with-angular-js-25112012.html

答案 3 :(得分:0)

尝试将此添加到你的angjularjs

    $(".yourTabClassName anchorTag").click(function(anyName) {
        anyName.preventDefault();
    });

例如:

    $(".nav a").click(function(e) {
        e.preventDefault();
    });

答案 4 :(得分:0)

哥们,我认为你缺少角色='tab'属性,它不会调用角度路由器

答案 5 :(得分:0)

您可以使用data-target="#tab1"代替href="#tab1"

答案 6 :(得分:0)

我通过这样做使它起作用。您会注意到我在“个人资料”选项卡窗格中使用<app-tab-profile></app-tab-profile>。我不确定这是否是最佳做法,但似乎可行。没有为TabProfileComponent设置路由。

<div class="section-container">
<ul class="nav nav-tabs" id="myTab" role="tablist">
    <li class="nav-item">
      <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Home</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Profile</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" id="contact-tab" data-toggle="tab" href="#contact" role="tab" aria-controls="contact" aria-selected="false">Contact</a>
    </li>
  </ul>
  <div class="tab-content" id="myTabContent">
    <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">...</div>
    <div class="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab"><app-tab-profile></app-tab-profile></div>
    <div class="tab-pane fade" id="contact" role="tabpanel" aria-labelledby="contact-tab">...</div>
  </div>

enter image description here

希望这会有所帮助!

答案 7 :(得分:-1)

    /**
     * This a callback object for the {@link ImageReader}. "onImageAvailable" will be called when a
     * still image is ready to be saved.
     */
    private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
            = new ImageReader.OnImageAvailableListener() {

        @Override
        public void onImageAvailable(ImageReader reader) {
            Log.d(TAG,"onImageAvailable");

            //Get the image
            Image cameraImage = reader.acquireNextImage();

            //Now unlock the focus so the UI does not look locked - note that this is a much earlier point than in the
            //original Camera2Basic example from google as the original place was causing the preview to lock during any
            //image manipulation and saving.
            unlockFocus();

            //Save the image file in the background - note check you have permissions granted by user or this will cause an exception.
            mBackgroundHandler.post(new ImageSaver(getActivity().getApplicationContext(), cameraImage, outputPicFile);

        }

    };