强制 angularjs 属性指令不解析其值

Force angularjs attribute directive to not parse its value

我正在制作一个类似于 ng-if 的属性指令。

window-match-media="(min-width: 400px)"

这将使元素在媒体查询匹配时呈现,否则消失。我正在为 ngIf

的代码建模我的指令

除了我目前必须用一对额外的引号将媒体查询括起来外,它工作得很好。这是因为没有它,它似乎试图parse the attribute value。这对 ngIf 有意义,但在我的例子中,我只想将该值视为字符串。

我在 ngIf 代码库中看不到任何允许我指示不应解析该值的内容,并添加

  scope: {
    windowMatchMedia: '@',
  },

没有帮助(我不确定属性指令是否可以隔离作用域?)。

我通过指令的 link 函数的 $attributes 参数访问该值,它总是 确实 似乎以字符串形式提供它,但是如果我不要专门用引号将其作为一个 ie

window-match-media="'(min-width: 400px)'"

由于解析问题,在我的指令有机会 运行 之前我收到一个错误。 如何告诉属性指令不解析它的值?我在 $compile 文档中没有看到任何相关信息。

编辑: 这是一个演示该问题的 Plunkr。在我按照我想要的方式工作并记录它之后,我可能应该开源它

Note how in this example, there is an error in the console

If I surround the attribute in quotes it works 因为解析器将其检测为字符串。但我根本不想涉及解析器。我想写一个普通的ol'属性值。

我希望第一个示例中的属性语法能够工作。

plunk中的例子有问题:

$scope.$watch($attr.windowMatchMedia, windowMatchMediaWatchAction);

这里的错误是属性值被提供给 $scope.$watch - 如果它不是有效的表达式,将导致解析错误。

如果不需要插入指令属性,则不应将其绑定到范围。相反,可以使用 $attr.$observe

$attr.$observe('windowMatchMedia', windowMatchMediaWatchAction);

同时

  scope: {
    windowMatchMedia: '@',
  },

是使用单向绑定执行此操作的正确方法,尽管隔离作用域限制了指令的使用方式。它允许提供 window-match-media 作为表达式和 doesn't require to use quotes for strings

不限制范围但允许在指令属性中使用表达式的通用方法涉及$attr.$observe

那么属性值可以是interpolated with $interpolate service against current scope:

var windowMatchMedia = $interpolate($attr.windowMatchMedia)($scope);
$window.matchMedia(windowMatchMedia);