为什么我的角度范围不受此指令限制?

时间:2015-10-08 12:54:19

标签: angularjs scope directive

我在下面有以下指令来创建标签功能。不幸的是,当我创建多个 这些标签的实例出错了。第一组选项卡仅切换第二组选项卡的显示。我错过了什么?

http://jsfiddle.net/U3pVM/19281/

core.directive("pane", function () {
        return {
            require: "^tabs",
        restrict: "A",
        transclude: true,
        scope: {
            title: "@"
        },
        link: function (scope, element, attrs, tabsCtrl) {
            tabsCtrl.addPane(scope);
        },
        template:
          '<div class="tab-pane" ng-class="{active: selected}"' +
            'ng-transclude></div>',
        replace: true
    };
});

core.directive("tabs", function () {
    return {
        restrict: "A",
        transclude: true,
        //$scope is injected in to a controller via dependency injection hence the use of $scope not scope 
        controller: function ($scope, $element) {
            var panes = $scope.panes = [];

            $scope.select = function (pane) {
                angular.forEach(panes, function (pane) {
                    pane.selected = false;
                });
                pane.selected = true;
            };

            this.addPane = function (pane) {
                if (!panes.length) $scope.select(pane);
                panes.push(pane);
            };
        },
        template:
          '<div class="tabs">' +
            '<ul class="nav nav-tabs">' +
              '<li ng-repeat="pane in panes"' +
                  'ng-class="{active:pane.selected}">' +
                '<a href="" ng-click="select(pane)">{{pane.title}}</a>' +
              '</li>' +
            '</ul>' +
            '<div class="tab-content" ng-transclude></div>' +
          '</div>',
        replace: true
    };
});

2 个答案:

答案 0 :(得分:3)

您需要在tabs指令上添加一个隔离(或子)范围。

core.directive("tabs", function () {
    return {
        restrict: "A",
        transclude: true,
        scope: {}, // <== here it is!
        controller: function ($scope, $element) {
            var panes = $scope.panes = [];

            $scope.select = function (pane) {
                angular.forEach(panes, function (pane) {
                    pane.selected = false;
                });
                pane.selected = true;
            };

            this.addPane = function (pane) {
                if (!panes.length) $scope.select(pane);
                panes.push(pane);
            };
        },
        template: '',
        replace: true
    };
});

这是因为您现在正在使用父作用域,因此为您使用的每个制表符指令覆盖该作用域上的面板属性。如果使用隔离范围,则为每个选项卡指令创建一个新的面板数组。

请参阅更新的小提琴:http://jsfiddle.net/basslagter/U3pVM/19287/

您也可以使用子范围,但这取决于您是否要使用父范围的属性。我现在要去隔离范围了。

答案 1 :(得分:3)

在标签上设置范围:true!

http://jsfiddle.net/U3pVM/19289/

 return {
    restrict: "A",
    transclude: true,
    scope: true,  <<missing this

这会创建一个子范围,如果您希望它是隔离的,请使用 -

 scope: {},