无法访问指令作用域中的rootscope var



下面的函数在rootscope中定义了一个变量。

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依赖于rootscope-中的一个变量

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"var,它就会起作用。

您的指令中有一个隔离作用域

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'}];
});

尝试:

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

最新更新