2014-12-23 78 views
1

我遇到問題以防止標籤切換。 這是搶劫犯。 http://plnkr.co/edit/v1i1cmBzqGo7hmWkhIh4?p=preview 當用戶點擊'Alert'選項卡時,我想要做一些條件測試,並且防止沒有選擇'Alert'選項卡。 我該怎麼做? 另一個問題是每個選項卡與UI狀態關聯的時間。 當選項卡更改時,UI狀態也在變化。 我想阻止這一點,我做了這個代碼。Angular UI Bootstrap Tabset:防止標籤切換

$rootScope.$on('$stateChangeStart', 
     function(event, toState, toParams, fromState, fromParams){ 
      event.preventDefault(); 

      destinationTab.active = false; 
      sourceTab.active = true; 
     }); 

然後,在此代碼後,原始選項卡不活動。

回答

0

我也遇到過這個問題,並寫了一個小指令來解決它。這是超級黑客,但基本上它會查找所有標籤頁的鏈接,添加一個點擊事件,翻轉每個鏈接的事件順序,讓我們的事件在angulars之前觸發,然後使用promise來允許控制器方法控制標籤切換。這應該與他們的選擇/取消選擇屬性一起工作。

指令:

.directive('tabPrevent', ['$q', '$timeout', function ($q, $timeout) { 
    'use strict'; 

    return { 
     restrict: 'A', 
     link: function (scope, element, attrs) { 
      var tabHeadings = element.find('ul li a'), 
        tabEvents = []; 

      if (attrs.tabPrevent) { 
       tabHeadings.bind('click', function (e) { 
        e.stopImmediatePropagation(); 

        var deferred = $q.defer(), 
          self = this, 
          tabIndex = -1 

        // find tab index for tabEvents reference 
        angular.forEach(tabHeadings, function (tab, index) { 
         if (tab === self) { 
          tabIndex = index; 
         } 
        }); 

        // call controller method, passing promise 
        scope.$eval(attrs.tabPrevent + '(deferred)', { deferred: deferred }); 

        deferred.promise.then(function (success) { 
         // initiate call to next event in array, which switches the tab 
         $timeout(function() { 
          tabEvents[tabIndex].click[1].handler(e); 
         }); 
        }); 
       }); 

       // flip event order to make our event fire before angular's 
       angular.forEach(tabHeadings, function (tabHeading) { 
        var clickEvents = $._data(tabHeading, "events"); 
        tabEvents.push(clickEvents); // save list of click events 
        clickEvents.click.unshift(clickEvents.click.pop()); // reverse events 
       }); 
      } 
     } 
    }; 

}]); 

HTML:

 <tabset tab-prevent="checkTab"> 
      <tab heading="{{tabs[0].title}}" active="tabs[0].active">Tab 1</tab> 
      <tab heading="{{tabs[1].title}}" active="tabs[1].active">Tab 2</tab> 
      <tab heading="{{tabs[2].title}}" active="tabs[2].active">Tab 3</tab> 
     </tabset> 

控制器:

$scope.checkTab = function (deferred) { 
     if ($scope.form && $scope.form.$dirty) { 
      deferred.reject(); // stops tab switch 
     } else { 
      deferred.resolve(); // allows tab swtich 
     } 
    };