AngularJS 和 AngularUI Bootstrap 添加新标签时双标签

AngularJS and AngularUI Bootstrap doubling tabs when adding a new tab

我正在尝试为每个新的 AngularUI 选项卡构建一个可重复使用的指令(具有隔离范围)。当我尝试收集一个选项卡内的所有数据并添加一个新选项卡时,Angular 实际上所做的是将我现有的选项卡加倍并收集每个现有选项卡的数据,每次我按 "Add new tab"。

请看下面plunker.

基本上,“添加新选项卡”按钮将广播在 TabController 内部处理的 collectDataFromCurrentTab 消息。见下文:

app.controller('TabController', function($scope, $rootScope) {
console.log("Scope id in tab is: " + $scope.$id);

$rootScope.$on('collectDataFromCurrentTab', collectDataFromTab);

function collectDataFromTab() {
    console.log("Scope id in collectDataFromCurrentTab: " + $scope.$id);
    var collector = {};
    collector.currentName = $scope.name;
    collector.currentAddress = $scope.address;

    $rootScope.collectedData.push(collector);

    console.log("Collected data: " + collector.currentName + " - " + collector.currentAddress);

    $rootScope.$broadcast('addNewTab');
}

app.controller('NavigationController', function($scope, $rootScope) {
$scope.addNewTab = function() {
    $rootScope.$broadcast('collectDataFromCurrentTab');
}

对此有任何解决方法吗?

$rootScope.$broadcast('addNewTab'); 移到 NavigationController$scope.addNewTab 函数中。不要从你的 TabController 广播 addNewTab,因为你有多个 Tab $scope,你广播了多次 addNewTab。确保修复你的 plunker,你已经 NavigationController 重复了两次。