0

so here is my custom directives sample code

myApp.directive('anchorLink', function () {
    return {
        restrict: 'EA',
        link: function (scope, elem, attr) {
            elem.on('click', function () {
                scope.show = true;
            });
        }
    };
});

and here's my html markup

<a href="javascript:;" anchor-link>click me</a>
<div ng-show='show'>show me</div>
<div ng-hide='show'>hide me</div>

as you can see I want to manipulate the $scope.show outside the custom directives environment but it didn't work.. can you help me?

Eka RudiAnto
  • 61
  • 3
  • 15

1 Answers1

0

You can either do this:

<a href="javascript:;" ng-click="show=true">click me</a>
<div ng-show='show'>show me</div>
<div ng-hide='show'>hide me</div>

or:

myApp.directive('anchorLink', function () {
    return {
        restrict: 'EA',
        link: function (scope, elem, attr) {
            elem.on('click', function () {
                scope.$apply(function (){
                   scope.show = true;
                });
            });
        }
    };
});

If the only purpose of your directive is bind a click handler you don't need a directive to do that since you can simply use ng-click.

Working plnkr of second option: plnkr

Wawy
  • 6,259
  • 2
  • 23
  • 23
  • well actually I want to manipulate DOM so I use custom directives, btw I tried using scope.$apply and it says $digest already in progress error ? – Eka RudiAnto Jul 02 '14 at 18:00
  • Hmm, did you add the ng-click too? it should be either one or the other. Also use double quotes in ng-show/ng-hide instead of single quotes. – Wawy Jul 02 '14 at 18:16
  • I'm using the second method though still using custom directives instead passing the ng-click into controllers.. yap I'm using double quotes instead of single quotes.. is there anything I'm missing ? – Eka RudiAnto Jul 02 '14 at 18:22
  • Look at the plnkr I added. It works just fine, you must have some other code that's making it error. – Wawy Jul 02 '14 at 18:38
  • I noticed that angularjs version that you used is 1.3.0 while I'm using 1.0.7 is the version of angularjs get an impact on this ? and I tried your plunkr but it doesn't toggle just manipulating the ng-show behaviour but I don't know – Eka RudiAnto Jul 03 '14 at 02:39
  • Try to update the version and see if it makes a difference. What do you mean the plnkr doesn't work? – Wawy Jul 03 '14 at 11:15