简体   繁体   English

在html中访问动态$ scope变量

[英]Access dynamic $scope variable inside html

I'm creating a large amount of directives and all will include dynamic scope variables that will be initialised inside the link functions eg: 我正在创建大量的指令,并且所有指令都将包含将在链接函数内初始化的动态范围变量, 例如:

//
link: function(scope, ele, attr){
  scope.key = scope.somevar + 'something_else';
  scope[scope.key] = 'the_value';
}
//

I want to access the value in the templates of the directives via scope.key . 我想通过scope.key访问指令模板中的值。

<div ng-if="scope[key]"> something </div>

Currently I only see it been viable through a function call like so: 目前我只通过函数调用看到它是可行的:

html HTML

<div ng-if="scope(key)"> something </div>

js JS

scope.scope = function(key) {
  return scope[key];
}

But then the problem is I will need to copy this into all the directives. 但问题是我需要将其复制到所有指令中。

Another option I considered was to assign the getter function onto the $rootScope making it globally accessible but how do I bind it to or pass in the current directives scope. 我考虑的另一个选项是将getter函数分配给$rootScope使其可全局访问,但如何将其绑定到或传入当前指令范围。 (If even possible). (如果可能的话)。

What would be a good approach to this? 对此有什么好处?

Inside of Angular template this keyword points to the current evaluation context, ie current scope. 在Angular模板内部, this关键字指向当前评估上下文,即当前范围。 It means that you would be able to achieve what you are after by using bracket notation on the this object: 这意味着您可以通过在this对象上使用括号表示法来实现您的目标:

<div ng-if="this[key]"> something </div>

Use bindToController option in your directive 在指令中使用bindToController选项

JS JS

bindToController: true,
controller: 'MyController',
controllerAs: 'ctrl',
link: function(scope, ele, attr){
  scope.ctrl.key = scope.somevar + 'something_else';
  scope.ctrl[scope.ctrl.key] = 'the_value';
}

HTML HTML

<div ng-if="ctrl[ctrl.key]"> something </div>

Check this codepen as example: http://goo.gl/SMq2Cx 检查此codepen作为示例: http//goo.gl/SMq2Cx

It would be easier to see all your code, but it sounds like you could just create a function on your scope to retrieve the value: 查看所有代码会更容易,但听起来您可以在范围上创建一个函数来检索值:

scope.getValue = function() {
    return scope[scope.key];
}

Then in your HTML: 然后在你的HTML中:

<div ng-if="getValue()"> something </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM