为什么 ng-style 不能在与自定义指令相同的元素上工作? [英] Why does ng-style not work on the same element as a custom directive?

查看:23
本文介绍了为什么 ng-style 不能在与自定义指令相同的元素上工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在自定义指令标签上应用 ng-style 属性,就像这样:

I'm trying to apply the ng-style attribute on a custom directive tag, kind of like so:

<my-directive ng-style="myStyle"></my-directive>

在控制器内部我有:

$scope.myStyle = {
    "background": "red"
}

虽然这似乎不起作用.当我检查 HTML 'MyStyle' 没有得到呈现.当我在常规 div 上应用相同的 ng-style 标签时,它会正确呈现.

This doesn't seem to work though. When I inspect the HTML 'MyStyle' does not get rendered. When I apply the same ng-style tag on a regular div it does render properly.

为什么 ng-style 不适用于自定义指令标签?

Why doesn't ng-style work on custom directive tags?

推荐答案

您的指令可能定义了一个隔离范围:scope: { ... }.在这种情况下,在该元素上定义的所有指令都将使用隔离范围.因此,ng-style 将在隔离范围内查找不存在的属性 myStyle.

Your directive likely defines an isolate scope: scope: { ... }. In that case, all directives defined on that element will use the isolate scope. Therefore, ng-style will look for property myStyle on the isolate scope, which doesn't exist.

上图中,灰色线表示$parents,虚线表示原型继承.Scope 004 是您的隔离范围.Scope 003 是您的控制器范围.ng-style 会在范围 004 中寻找 myStyle ,没有找到,然后它会沿着虚线在 Scope 中寻找它,也没有在那里找到.

Above, gray lines show $parents, dashed lines show prototypal inheritance. Scope 004 is your isolate scope. Scope 003 is your controller scope. ng-style will look for myStyle in scope 004, not find it, then it will follow the dashed line and look for it in Scope, and not find it there either.

通常,您不希望使用在同一元素上创建隔离作用域的指令以及其他指令.您有几个选择:

Normally you don't want to use directives that create an isolate scope along with other directives on the same element. You have a few options:

  1. 在指令中使用 scope: true 而不是隔离范围.然后当ng-style在作用域004中寻找myStyle但没有找到时,它会沿着虚线(下图)在父作用域中找到:
  2. 在 HTML 中使用 ng-style="$parent.myStyle" 访问父作用域中的 myStyle 属性(即,按照第一个灰线图片).
  1. use scope: true instead of an isolate scope in your directive. Then when ng-style looks for myStyle in scope 004 and doesn't find it, it will then follow the dashed line (in the picture below) and find it in the parent scope:
  2. use ng-style="$parent.myStyle" in your HTML to access the myStyle property in the parent scope (i.e., follow the gray line in the first picture).

这篇关于为什么 ng-style 不能在与自定义指令相同的元素上工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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