0

I have a scenario where when i mouse enter on some text i need to get an input box and text should hide and when i leave the text box the box should hide and i should show the text back

but this is not happening

Html

<div ng-app>
<div ng-controller="showCrtl">
   <div ng-hide="showme">
     <p ng-mouseenter="showme=!showme">
       mouse enter
     </p> 
   </div>
   <input type="search" ng-if="showme" ng-mouseleave="showme=false">
 </div>
</div>

JS:

function showCrtl($scope){
  $scope.showme=false;
}

Here is what i have tried DEMO

Any help is appreciated.

Andrew Eisenberg
  • 28,387
  • 9
  • 92
  • 148
Shikha thakur
  • 1,269
  • 13
  • 34

2 Answers2

2

The problem is you had primitive value on ng-if directive, You know ng-if does create child scope whenever it renders that element on DOM. To resolve this issue what I'd suggest you to do is, just follow Dot Rule by defining new object. And then define all the property which you want to use inside that object.

If you want do dig deeper how scope inheritance work, you can refer to this answer.

So in your code, you should define an object suppose i.e. $scope.model = {} and then have showme property inside that object itself. And wherever you use showme on view replace that with model.showme.

Demo Fiddle


More convenient way to resolve such kind of scope inheritance issue is, you could use controllerAs pattern. In that you don't use $scope inside controller, you just place with controller context this. While using controller on view you need to create it alias and when you want to get variable value you can use variable reference.

Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • 1
    @Shikhathakur Glad to help you, look at the updated answer, would help you more to clear understandings. Read referred answer as well, Thanks :) – Pankaj Parkar Jul 23 '16 at 15:18
1

The issue is that you have multiple nested scopes. The showme that is being set in the input box is different from the showme being set in the p. This happens because Angular implicitly adds a new scope for many built-in directives (ng-if is one of them).

You need to be sure that you are always setting and reading the same showme property. The easiest way to do this is to add the showme property to the controller.

Try this:

<div ng-app>
   <div ng-controller="showCrtl">
     <div ng-hide="showCrtl.showme">
       <p ng-mouseenter="showCrtl.showme=!showCrtl.showme">
         mouse enter
       </p> 
     </div>
     <input type="search" ng-if="showCrtl.showme" ng-mouseleave="showCrtl.showme=false">
   </div>
</div>

In fact, as a general rule of thumb, never access the scope directly in your templates since it is very difficult to be sure you are accessing the scope that you think you are accessing. Always access properties through the controller you are working with.

Andrew Eisenberg
  • 28,387
  • 9
  • 92
  • 148