无法访问指令范围内的 rootscope var [英] unable to access rootscope var in directive scope

查看:29
本文介绍了无法访问指令范围内的 rootscope var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的函数在 rootscope 中定义了一个变量.

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

下面指令中的 html 依赖于 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.

推荐答案

你的指令中有一个 isolate 作用域

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: '='}

然后像这样调用指令

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

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

此外,您可能希望从 run 方法中修改 $rootScope,而不是从控制器中修改 $rootScope

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

这篇关于无法访问指令范围内的 rootscope var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆