加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 无法在指令范围内访问rootscope var

发布时间:2020-12-17 07:41:56 所属栏目:安全 来源:网络整理
导读:下面的函数定义了根镜中的一个变量. 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'
下面的函数定义了根镜中的一个变量.
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中的变量 –

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

但是上面的代码不行.如果我直接在指令范围中定义了“buttons”var,它将起作用.

您的指令中有一个隔离范围
scope:{}

这意味着该指令无法访问上层范围 – 请记住隔离范围不会从父范围原型继承.因此,您可以删除隔离范围,也可以告诉该指令将一些属性与父范围的本地范围绑定.

scope: {buttons: '='}

然后调用这样的指令

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

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

另外,不要从控制器修改$rootScope,您可能希望从run方法中执行此操作

var app = angular.module('app',['btnbar.directive']);

app.run(function($rootScope){
  $rootScope.buttons = [{href: '#/students',icon:'icon-plus'}];
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读