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

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

问题描述

我想申请一个自定义指令标签的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"
}

这似乎并没有工作,虽然。当我检查HTMLmyStyle的没有得到呈现。当我申请定期DIV相同NG式标签它正确地呈现。

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-的工作作风?

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

推荐答案

您可能指令的定义范围隔离:范围:{...} 。在这种情况下,该元素上定义的所有指令将使用分离范围。因此,吴式将查找财产 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.

以上,灰线显示$父母,虚线表示原型继承。
范围004是你的分离范围。范围003是你的控制器范围。 NG-风格会寻找 myStyle的范围004,找不到的话,那么它会按照虚线和范围寻找它,而不是在那里找到它的。

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. 使用范围:真正的而不是在你的指令的分离范围。然后,当NG-风格范围004查找 myStyle的并没有找到它,它会然后按照虚线(如下图),并发现它的父适用范围:结果

  2. 使用 NG-风格=$ parent.myStyle在你的HTML来访问的 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-风格不为自定义指令相同的元素上工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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