I have a directive that I use like this:
<dir model="data"></dir>
The directive has an isolated scope.
scope :{ model:'=' }
Now I'm trying to use ng-show
on that directive using another attribute of my page's $scope, like this:
<dir ng-show="show" model="data"></dir>
But it's not working because the directive is trying to find the show
attribute on its own scope.
I don't want the directive to know about the fact that its container might choose to hide it.
The workaround I found is to wrap the directive in a <div>
and apply ng-show
on that element, but I don't like the extra element this forces me to use:
<div ng-show="show" > <dir model="data"></dir> </div>
Is there a better way of doing this?
See this plunker: http://plnkr.co/edit/Q3MkWfl5mHssUeh3zXiR?p=preview
The difference between is : ng-show directive will show the html element if expression resilts is true and ng-hide directive hide the html element if expression result is true .
AngularJS ng-show DirectiveThe ng-show directive shows the specified HTML element if the expression evaluates to true, otherwise the HTML element is hidden.
ng-if can only render data whenever the condition is true. It doesn't have any rendered data until the condition is true. ng-show can show and hide the rendered data, that is, it always kept the rendered data and show or hide on the basis of that directives.
Isolated scope directive is a scope that does not inherit from the parent and exist on its own. Scenario: Lets create a very simple directive which will show the object from the parent controller.
Update: This answer applies to Angular releases prior to 1.2. See @lex82's answer for Angular 1.2.
Because your dir
directive creates an isolate scope, all directives defined on the same element (dir
in this case) will use that isolate scope. This is why ng-show
looks for property show
on the isolate scope, rather than on the parent scope.
If your dir
directive is truly a standalone/self-contained/reusable component, and therefore it should use an isolate scope, your wrapping solution is probably best (better than using $parent
, IMO) because such directives should normally not be used with other directives on the same element (or you get exactly this kind of problem).
If your directive doesn't need an isolate scope, your problem goes away.
You could consider migrating to Angular 1.2 or higher. The isolate scope is now only exposed to directives with a scope property. This means the ng-show is not influenced by your directive anymore and you can write it exactly like you tried to do it in the first place:
<dir ng-show="show" model="data"></dir>
@Angular-Developers: Great work, guys!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With