unable to access rootscope var in directive scope

后端 未结 2 1583
长情又很酷
长情又很酷 2021-01-04 07:55

The function below defines a variable in the rootscope.

function MyCtrl($scope, $rootScope) {
  $rootScope.buttons = [{href: \'#/students\', icon:\'icon-ok\         


        
相关标签:
2条回答
  • 2021-01-04 08:06

    Try:

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

    0 讨论(0)
  • 2021-01-04 08:10

    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'}];
    });
    
    0 讨论(0)
提交回复
热议问题