我也遇到過這個問題,並寫了一個小指令來解決它。這是超級黑客,但基本上它會查找所有標籤頁的鏈接,添加一個點擊事件,翻轉每個鏈接的事件順序,讓我們的事件在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
}
};