Why ng-hide doesn't work with custom directives?

不打扰是莪最后的温柔 提交于 2019-12-19 05:45:19

问题


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': '='
  },

回答1:


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.




回答2:


your can change the

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

to

 <my-dialog ng-hide="$parent.dialogIsHidden" on-close="hideDialog()">


来源:https://stackoverflow.com/questions/19850804/why-ng-hide-doesnt-work-with-custom-directives

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!