Failed to access root var var in scope

The function below defines the variable in the root directory.

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

The html in the directive below depends on the variable in the root crops -

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

However, the above code does not work. It works if I directly define var "buttons" in the scope.

+12
angularjs angularjs-scope
Dec 15 '12 at 18:51
source share
2 answers

Isolate in your directive

 scope:{} 

This means that the directive does not have access to the upper regions - remember that selection regions are not prototypically inherited from the parent region. Thus, you either remove the isolation region or tell the directive to associate some properties with its local region from the parent region.

 scope: {buttons: '='} 

Then call a directive like this

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

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




Alternatively, instead of changing $rootScope from the controller, you can do this using the run method

 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'}]; }); 
+21
Dec 16 '12 at 2:18
source share

Try:

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

+19
Feb 21 '14 at 14:50
source share



All Articles