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

查看:145
本文介绍了无法访问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
  }
});

不过上述code不工作。它的工作原理,如果我直接在指令范围定义按钮变种。

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

推荐答案

您有一个分离范围在指令

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>

例如:<一href=\"http://plnkr.co/edit/88R66L7uAHoezDZvuoH5?p=$p$pview\">http://plnkr.co/edit/88R66L7uAHoezDZvuoH5?p=$p$pview

此外,而不是修改 $ 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天全站免登陆