下面的函数定义了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取决于rootcope中的变量 -
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,它就可以工作。
答案 0 :(得分:22)
您的指令
中有隔离范围scope:{}
这意味着该指令无法访问高端范围 - 请记住,隔离范围不是从父范围原型继承的。因此,您要么删除隔离范围,要么告诉指令将某些属性从父范围绑定到其本地范围。
scope: {buttons: '='}
然后像这样调用指令
<btn-bar buttons="buttons"></btn-bar>
示例:http://plnkr.co/edit/88R66L7uAHoezDZvuoH5?p=preview
此外,您可能希望从$rootScope
方法
run
。
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 :(得分:19)
尝试:
<a class="btn" ng-repeat="b in $root.buttons" href={{b.href}}>