Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-show not working inside directive template

I would like to do something like this fiddle, making the text disappear and reappear with every click.

Problem is, it seem that with an isolated scope you can't have access to the controller scope. I solved it in the link function, handling there click event and setting my "showMe" flag using scope.$apply, like:

scope.$apply('showMe = false');

Is this the right way to go or there is some more elegant method?

like image 568
Maddocche Avatar asked Nov 19 '25 21:11

Maddocche


1 Answers

Here you go (http://jsfiddle.net/66d0t7k0/1/)

Put your click handler in the link function and expose showMe to the scope

app.directive('example', function () {

    return {
        restrict: 'E',
        template: '<p ng-show=\"showMe\">Text to show</p><button ng-click=\"clickMe()\">Click me</button>',
        scope: {
            exampleAttr: '@'
        },
        link: function (scope) {
            scope.clickMe = function () {
                scope.showMe = !scope.showMe;
            };
        }
    };
});
like image 80
apairet Avatar answered Nov 24 '25 10:11

apairet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!