【问题标题】:Why directives method is available from parent scope为什么指令方法可从父范围使用
【发布时间】:2023-04-04 05:35:01
【问题描述】:

AngularJS v1.2.28

这是我的侧边栏控制器:

angular.module('core').controller('SidebarController', ['$scope', '$location',
    function($scope, $location) {

        $scope.isItemActive = function (section) {
            return ($location.path() === section);
        };
    }
]);

还有侧边栏的模板:

<section  data-ng-controller="SidebarController">
        <a ui-sref="dashboard.new-subscription"
           ui-route="/dashboard/subscription/new"
           class="item "
           ng-class="{active: isItemActive('/dashboard/subscription/new')}"> 
            + New Subscription
        </a>

        <subscriptions-list></subscriptions-list>
</section>

订阅列表的指令:

angular.module('core').directive('subscriptionsList', ['Subscription', '$state', '$location',
    function(Subscription, $state, $location) {
        return {
            templateUrl: '/modules/core/views/subscriptions-list.client.view.html',
            restrict: 'E',
            link: function postLink(scope, element, attrs) {
                ....

                scope.isItemActive = function(path, subscription) {
                    var curPath = path + '/' + subscription._id;
                    return ($location.path() === curPath);
                };
            }
        };
    }
]);

如您所见,控制器和指令都具有 isItemActive 函数。 出于某种原因,当我在侧边栏模板中调用 isItemActive('/dashboard/subscription/new') 时,出现错误“无法读取未定义的属性 '_id'”,因为它从 subscriptionsList 指令而不是控制器指令调用 isItemActive()。

这怎么可能?如何在指令范围之外访问指令中的方法?这个方法我没有使用绑定..

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    您的指令不使用隔离范围,也不创建子范围。你在指令中用来声明isItemActive 的作用域实际上就是指令使用的作用域,与控制器的作用域相同。你基本上覆盖了你的控制器的isItemActive

    您需要使用scope: {} 使用隔离作用域或使用scope: true 创建子作用域。

    您可以在此处阅读有关差异的更多信息:https://github.com/angular/angular.js/wiki/Understanding-Scopes

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-06
      • 2016-03-13
      • 1970-01-01
      • 2017-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多