Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to access rootscope var in directive scope

The function below defines a variable in the 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'];

The html in the directive below depends upon a variable in the 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
  }
});

However the above code doesnt work. It works if I directly define the 'buttons' var in the directive scope.

like image 209
murtaza52 Avatar asked Dec 15 '12 18:12

murtaza52


1 Answers

You have an isolate scope in your directive

scope:{}

This means that the directive doesn't have access to upper scopes - remember that isolate scopes don't prototypically inherit from the parent scope. So you either remove the isolate scope or tell the directive to bind some properties to its local scope from the parent scope.

scope: {buttons: '='}

Then invoke the directive like this

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

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


Also, rather than modifying the $rootScope from a controller, you might want to do it from 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'}];
});
like image 169
jaime Avatar answered Jan 05 '23 00:01

jaime