在HTML中访问动态$ scope变量 [英] Access dynamic $scope variable inside html

查看:379
本文介绍了在HTML中访问动态$ scope变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建大量指令,并且所有指令都将包含动态范围变量,这些变量将在链接函数内部初始化 例如:

I'm creating a large amount of directives and all will include dynamic scope variables that will be initialised inside the link functions e.g:

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

我想通过scope.key访问指令模板中的值.

I want to access the value in the templates of the directives viascope.key.

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

目前,我仅通过如下这样的函数调用看到它是可行的:

Currently I only see it been viable through a function call like so:

html

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

js

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

但是问题是我需要将其复制到所有指令中.

But then the problem is I will need to copy this into all the directives.

我考虑的另一个选项是将getter函数分配到$rootScope上,使其可以全局访问,但是如何将其绑定到或传递给当前指令范围. (如果可能的话).

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. (If even possible).

什么是一种好的方法?

推荐答案

在Angular模板内this关键字指向当前评估上下文,即当前范围.这意味着您可以通过在this对象上使用括号表示法来实现自己想要的目标:

Inside of Angular template this keyword points to the current evaluation context, i.e. current scope. It means that you would be able to achieve what you are after by using bracket notation on the this object:

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

这篇关于在HTML中访问动态$ scope变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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