Ng-show does not work inside directive template

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

The problem is that with an isolated scope, you cannot access the controller scope. I solved this in the links function by handling the click event there and setting the "showMe" flag using the scope. $ Apply , for example:

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

      

Is this correct, or is there a more elegant method?

+3


source to share


3 answers


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

Place your click handler in your link function and output showMe

toscope



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;
            };
        }
    };
});

      

+5


source


To expand on apairet's answer, since your directive uses isolated scoping, you can handle the whole thing in the template itself like so:

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

    return {
        restrict: 'E',
        template: '<p ng-show=\"showMe\">Text to show</p><button ng-init=\"showMe = false\" ng-click=\"showMe = !showMe\">Click me</button>',
        scope: {
            exampleAttr: '@'
        },
        link: function (scope) {

        }
    };
});

      



Another consideration is to use ng-if rather than ng-show, as it does not display the element in the DOM until the expression evaluates to true.

+1


source


You can hide the scope in the directive by setting scope: false Then you can put your entire function in the scope of the main controller.

angular.module('appMyApp').directive('appMyAppItem', function() {
    return {
        transclude: true,
        templateUrl: 'link/to/url',
        controller: 'appMyAppController',
        scope: false
    }
});


angular.module('appMyApp').controller('appMyAppController', ['$scope', function($scope){

    $scope.showItem = true;
    $scope.toggleItem = function(){
        $scope.showItem = !$scope.showItem;
    };
}]);

      

Hope it helps

0


source







All Articles