Search code examples
angularjsangular-ui-bootstrapangular-ui

angular-ui-bootstrap, remove the last tab, the whole page was refreshed


I added ng-click event to remove the tab in uib-tab-heading.Everything was ok but when I removed the last tab, the whole page was refreshed which is not expected. This is my code: http://embed.plnkr.co/f0p9uZgKuWTNh3Ss7okY.

html

  <head>
    <link data-require="bootstrap-css@3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css" />
    <script data-require="angularjs@1.6.2" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-controller="TabsDemoCtrl">
      <uib-tabset active="active">
        <uib-tab index="0" heading="Static title">Static content</uib-tab>
        <uib-tab index="$index+1" ng-repeat="tab in tabs  track by $index">
          <uib-tab-heading>
                    {{tab.title}}
              <div class="close" aria-label="Close" ng-click="remove($index)">
              <span aria-hidden="true">×</span>
            </div>
            <!--<div style="width: 10px; height: 10px; background-color: red;" ng-click="removeTab($index)"></div>-->
          </uib-tab-heading>


                {{tab.content}}
            </uib-tab>
      </uib-tabset>
    </div>
  </body>

</html>

js

angular.module('app', ['ui.bootstrap']).controller('TabsDemoCtrl', function ($scope, $window) {
    $scope.tabs = [{
            title: 'Dynamic Title 1',
            content: 'Dynamic content 1'
        },
        {
            title: 'Dynamic Title 2',
            content: 'Dynamic content 2',
        },
        {
            title: 'Dynamic Title 3',
            content: 'Dynamic content 3',
        },
        {
            title: 'Dynamic Title 4',
            content: 'Dynamic content 4',
        }   
    ];

    $scope.remove = function (index) {
        $scope.tabs.splice(index, 1);
        $scope.active = $scope.tabs.length;
    };
});

Thanks for your help.


Solution

  • <uib-tab-heading> itself is wrapped with <a> tag, so it seems like page refreshes due to default link click action.

    Do

    <div ng-click="remove($index, $event)">
    
    $scope.remove = function(index, event){
        event.preventDefault();
        ...
    }