Search code examples
angularjsangularjs-ng-include

Multiple ngIncludes with Different controls visible


I have a snippet of HTML with its own controller. I want to include that snippet in two different places.

If it is displayed as a child of #parent1, I want some fields hidden. If displayed as part of #parent2, I'd like other fields hidden.

I've done this before, but not when #parent1 and #parent2 can both be visible at the same time.

Thoughts?


Solution

  • You are at the point where you should probably stop using ng-include and write a very simple directive instead. This is the typical use case of a angular directive with an isolated scope, just pass in a scope-variable and use it in your template with ngShow ngHide or ngIf:

     .directive('snippy', ['$rootScope',
            function ($rootScope) {
                return {
                    restrict: 'E',
                    scope: {
                        showit: '='
                    },
                    templateUrl: 'yoursnippet.html',
                    link: function(scope, elem, attrs) {
                       // here goes your controller code
                    }
             }
    

    and then in yoursnippet.html:

    <div>
       <div ng-show="showit">this is shown/hidden</div>
    </div>
    

    and then in your parent:

    <div>
        <snippy showit="anyangularexpression">
        <snippy showit="anyangularexpression2">
    </div>