无法在指令作用域中访问根作用域变量

14

下面的函数在根作用域中定义了一个变量。

function MyCtrl($scope, $rootScope) {
  $rootScope.buttons = [{href: '#/students', icon:'icon-ok'},
                         {href: '#/students', icon:'icon-remove'},
                         {href: '#/students/new', icon:'icon-plus'}];
}
MyCtrl.$inject = ['$scope', '$rootScope'];
以下指令中的HTML取决于根作用域中的一个变量-
angular.module('btnbar.directive', []).
directive("btnBar", function(){
  return {
    restrict: 'E',
    scope :{},
    controller: function($scope, $element,$rootScope) {
    },
    template:'<div class="btn-toolbar">' +
      '<a class="btn" ng-repeat="b in buttons" href={{b.href}}>' +
      '<i class={{b.icon}}></i></a></div>',
    replace:true
  }
});

然而上面的代码不起作用。如果我直接在指令范围内定义"buttons"变量,它就能起作用。

2个回答

23

您的指令具有隔离作用域。

scope:{}

这意味着该指令无法访问上层作用域 - 请记住,隔离作用域并不会从父级作用域原型继承。因此,您可以删除隔离作用域或告诉指令在其本地作用域中将一些属性绑定到父作用域。

scope: {buttons: '='}

然后像这样调用指令

<btn-bar buttons="buttons"></btn-bar>

示例:http://plnkr.co/edit/88R66L7uAHoezDZvuoH5?p=preview


此外,您可能希望从run方法中修改$rootScope而不是从控制器中进行修改。

var app = angular.module('app', ['btnbar.directive']);

app.run(function($rootScope){
  $rootScope.buttons = [{href: '#/students', icon:'icon-ok'},
                        {href: '#/students', icon:'icon-remove'},
                        {href: '#/students/new', icon:'icon-plus'}];
});

1
Jim,感谢您的回复。我有一个问题,为什么需要在属性中指定 buttons = "buttons"?它是做什么用的?如果没有上述属性声明,代码为什么不能正常工作? - murtaza52
由于指令控制器接受作用域(scope)、元素(element)、属性(attribute)和传递(transclude),因此您的第三个参数是$rootScope,实际上是属性参数。以下是您的控制器代码: function($scope, $element,$rootScope)。 现在请查看文档http://docs.angularjs.org/guide/directive。 - AsadYarKhan
@AsadYarKhan 我认为你把控制器和链接以及编译混淆了。 - Usagi

19
尝试:

<a class="btn" ng-repeat="b in $root.buttons" href={{b.href}}>

尝试:

这个答案结合问题标题更有意义。 - Alireza Mirian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接