0

I want to show element based on the value of property inside controller.

eReaderBook.directive("controlTools", function () {
return {
    replace : true,
    restrict : "E",
    templateUrl : "assets/directives/controlstools.html",
    controller : function ($scope) {
        $scope.visible = false;
    },
    link : function (scope, el, attr) {

       el.bind("mouseover",function()
        {
           console.log(scope.visible)
           scope.visible = true;
        });
        el.bind("mouseout",function()
        {
            console.log(scope.visible)
             scope.visible = false;
        })
    }
};

});

<div class="menuitem"><span class="glyphicon glyphicon-search"></span><span ng-show="visible" class="menutext">Toc</span></div>

Inside the directive I have a controller defined with $scope.visible = false. Everything works fine on page load. I want to change the state to $scope.visible = true on mouseover and $scope.visible = false on mouseout. Why does scope.visible = true; not affect ng-show?

ndsmyter
  • 6,535
  • 3
  • 22
  • 37
bharath
  • 845
  • 2
  • 11
  • 23
  • 4
    DOM events are outside of Angular. You need to inform Angular of the change with `$scope.$apply()`. Angular already has directives for this, so you don't need to create a new one. – m59 Jul 14 '15 at 10:14
  • 4
    Your event handling happens outside the *`$digest`-cycle*. Use [`$apply`](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply) or better [`ngMouseenter`](https://docs.angularjs.org/api/ng/directive/ngMouseenter). – Yoshi Jul 14 '15 at 10:14
  • possible duplicate of [How can I tell AngularJS to "refresh"](http://stackoverflow.com/questions/12304728/how-can-i-tell-angularjs-to-refresh) – m59 Jul 14 '15 at 10:15
  • 3
    Why not use `ng-mouseover="visible = true"` and `ng-mouseleave="visible = false"`? I think this is easier. E.g. `Toc`. – Alberto I.N.J. Jul 14 '15 at 10:19

1 Answers1

0

You just forgot to add scope: true that is responsible to share scope.

return {
  replace: true,
  restrict: "E",
  scope: true,
  templateUrl: "assets/directives/controlstools.html",
Snm Maurya
  • 1,085
  • 10
  • 12