为什么 ng-hide 不适用于自定义指令? [英] Why ng-hide doesn't work with custom directives?

查看:20
本文介绍了为什么 ng-hide 不适用于自定义指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 angularjs.org 上开发人员指南的指令部分以更新我的知识并获得一些见解,我试图运行其中一个示例,但指令 ng-hide 不适用于自定义指令.

这里是 jsfiddle:http://jsfiddle.net/D3Nsk/:

在这里不起作用!!!</my-dialog><div ng-hide="dialogIsHidden">它在这里工作.

知道为什么会这样吗?

解决方案

好像标签上的变量dialogIsHidden已经做了引用指向指令内的范围变量,而不是控制器中的变量;给予该指令有它自己的孤立范围,要使这项工作能够通过通过将控制器的变量 dialogIsHidden 引用到指令.

这里是jsfiddle:http://jsfiddle.net/h7xvA/

更改于:

 

和:

 范围:{'关闭': '&onClose','dialogIsHidden': '='},

解决方案

在将对象分配给作用域时,您在指令中创建了一个隔离的作用域.这就是为什么 $scope.dialogIsHidden 没有传递给指令,因此元素没有被隐藏.

Kain 建议使用 $parent 对小提琴进行调整说明了这一点.

I'm reading the directives section of the developers guide on angularjs.org to refresh my knowledge and gain some insights and I was trying to run one of the examples but the directive ng-hide is not working on a custom directive.

Here the jsfiddle: http://jsfiddle.net/D3Nsk/:

<my-dialog ng-hide="dialogIsHidden" on-close="hideDialog()">
  Does Not Work Here!!!
</my-dialog>
<div ng-hide="dialogIsHidden">
       It works Here.
</div>

Any idea on why this is happening?

Solution

Seems that the variable dialogIsHidden on the tag already make a reference to a scope variable inside the directive and not to the variable in the controller; given that the directive has it's own insolated scope, to make this work it's necesary to pass by reference the variable dialogIsHidden of the controller to the directive.

Here the jsfiddle: http://jsfiddle.net/h7xvA/

changes at:

 <my-dialog 
     ng-hide="dialogIsHidden" 
     on-close="hideDialog()" dialog-is-hidden='dialogIsHidden'>

and:

  scope: {
    'close': '&onClose',
    'dialogIsHidden': '='
  },

解决方案

You're creating an isolated scope inside your directive when asigning an object to scope. This is why $scope.dialogIsHidden is not passed through to the directive and thus the element is not being hided.

Kain's suggested adjustment for the fiddle with using $parent illustrates this.

这篇关于为什么 ng-hide 不适用于自定义指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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