2012-12-15 52 views
12

下面的函數在rootscope中定義了一個變量。下面無法訪問指令範圍內的rootcope var

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,它將起作用。

回答

21

你有一個在你的指令

scope:{} 

隔離範圍這意味着該指令沒有進入上範圍 - 請記住,隔離範圍不prototypically從父範圍繼承。因此,您要麼刪除隔離範圍,要麼告訴該指令將某些屬性從父範圍綁定到其本地範圍。

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

吉姆感謝偉大的答覆。一個問題,爲什麼我需要在我的屬性中指定按鈕=「按鈕」。它還有什麼作用?爲什麼在沒有上述屬性聲明的情況下不能執行代碼? – murtaza52

+0

因爲指令控制器接受scope,element,attribute和transclude,所以第三個參數是$ rootScope,它實際上是屬性參數。這裏是你的控制器代碼: 函數($ scope,$ element,$ rootScope)。 現在看到文檔http://docs.angularjs.org/guide/directive – AsadYarKhan

+0

@AsadYarKhan我認爲你混淆控制器與鏈接和編譯。 – Usagi

19

嘗試:

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

+0

考慮到問題的題目,這個答案更有意義 –