Search code examples
javascriptangularjsangularjs-directiveangular-ui

Is there a more elegant hide/show pattern in angular?


On a crowded screen I have it is is incorporating many ng-hide/ ng-show directives.

The common pattern to do that is:

<div  . . ng-hide="showCurveForm" ng-click="toggleCurveForm()">
                    Show Curve Form
</div>
<div  . . ng-show="showCurveForm" ng-click="toggleCurveForm()">
                    Hide Curve Form
</div>

Which is supported in the controller like so:

$scope.toggleCurveForm = function () {
   $scope.showCurveForm = !$scope.showCurveForm;
};

Question Are there patterns that do not require me cluttering my controller with many of these "switches?"

It just seems verbose. I only want to flip a Boolean while still following all the guides that say my controllers should be thin.


Solution

  • You can, of course, create your own directive. For example:

    app.directive('toggleThis', function(){
        return {
            restrict: 'E',
            template: '<div ng-hide="showCurveForm" ng-click="toggleCurveForm()">Show Curve Form</div>'+
        '<div ng-show="showCurveForm" ng-click="toggleCurveForm()">Hide Curve Form</div>'
        };
    });
    

    This way you can strip your HTML down to something like:

    <toggle-this></toggle-this>

    and it will be replaced with your directive template. In addition, this new directive can be used repeatedly throughout your site/app.

    See this fiddle for a working example, using your code above.