从指令控制器访问范围

时间:2013-05-30 18:34:57

标签: angularjs angularjs-directive

从指令中定义的控制器访问范围变量的正确方法是什么?

示例,我想让click事件在父指令的控制器上调用一个函数。在父指令中,我希望控制器能够访问“常量”,FOO_VIEW,BAR_VIEW,BAM_VIEW

将这些常量放在顶级控制器中是否更有意义,在本例中为SearchCtrl(未显示)?

指令:

.directive('usersAndApps', function() {
        return {
            restrict:'EA',
            scope: true,
            controller: function() {
                this.toggleView = function(viewName){
                    console.log('show view ' + viewName);
                }
            },
            link:function(scope, elem, attrs) {
                scope.FOO_VIEW = 'fooView';
                scope.BAR_VIEW = 'barView';
                scope.BAM_VIEW = 'bamView';
            }
        }
    }).directive('usersAndAppsNav', function() {
        return {
            restrict: 'AE',
            require:'^?usersAndApps',
            replace:true,
            scope:true,
            link:function(scope,elem,attrs,usersAndAppsCtrl){
                scope.toggleView = function(viewName){
                    usersAndAppsCtrl.toggleView(viewName);
                }
            },
            templateUrl:'partials/usersAndApps/throwmeaway'
        }
    });

模板:

<div>
    <button class="btn btn-large btn-primary" ng-click="toggleView(FOO_VIEW)">Foo View</button>
    <button class="btn btn-large btn-primary" ng-click="toggleView(BAR_VIEW)">Bar View</button>
    <button class="btn btn-large btn-primary" ng-click="toggleView(BAM_VIEW)">Bam View</button>
</div>

指令和嵌套(子)指令:

<div ng-controller="SearchCtrl">
    <users-and-apps>
        <users-and-apps-nav></users-and-apps-nav>
    </users-and-apps>
</div>

2 个答案:

答案 0 :(得分:1)

您所拥有的一切都很好,但由于您未在usersAndAppsNav中使用隔离或转换范围,因此您无需在usersAndApps上定义控制器API - 您可以简单地利用如果您在与toggleViewParent相关联的范围内定义方法usersAndApps,请prototypal scope inheritance

.directive('usersAndApps', function() {
return {
    restrict:'EA',
    scope: true,
    link:function(scope, elem, attrs) {
        scope.FOO_VIEW = 'fooView';
        ...
        scope.toggleViewParent = function(viewName){
            console.log('show view ' + viewName);
        }
    }
}
}).directive('usersAndAppsNav', function() {
return {
    restrict: 'AE',
    replace:true,
    scope:true,
    link:function(scope,elem,attrs) {
        scope.toggleView = function(viewName){
            scope.toggleViewParent(viewName);
        }
    },
   templateUrl: ...
}
});

Fiddle

enter image description here

请注意,当您在模板中编写ng-click="toggleView(FOO_VIEW)"时,您已经在使用原型继承 - FOO_VIEW评估为fooView的唯一原因是原型继承 - FOO_VIEW定义于与usersAndApps(范围004)关联的范围,子范围(范围005)通过继承链/查找(即,在虚线后面)找到。

答案 1 :(得分:-3)

请查看涵盖此主题的快速视频教程@ http://www.egghead.io/video/LJmZaxuxlRc

他还有一些其他非常棒的AngularJS教程视频链接到该网站。