Search code examples
angularjsangular-directiveng-hide

How to use ng-show and ng-hide in an angularjs custom directive's template?


I have searched all day for an answer and cannot seem to get this right.

I have a scope value profile_edit_mode being set to either true or false by clicking an edit button. This value then activates the ng-hide and ng-show on the form.

when I move this into a custom directive the ng-hide or ng-show won't work.

I have the following.

HTML Code

<bos-input fieldname="firstname" title="First Name" place-holder="First Name" ng-model="user_profile_details.firstname" edit-mode="{{profile_edit_mode}}"></bos-input>

Custom directive.

enter code hereangular.module('aesthetics')
.directive('bosInput', function(){
    return {
        restrict: 'E',
        require: 'ngModel',
        template: '<div class="form-group">' +
                    '<label for="{{fieldname}}" class="col-lg-3 control-label">{{title}}</label>' +
                        '<div class="col-lg-9">' +
                        '<input ng-show="editMode" class="form-control" id="{{fieldname}}" ng-model="ngModel" placeholder="{{placeHolder}}">' +
                        '<div class="m-t-xs" ng-hide="editMode">{{ngModel}}</div>' +
                    '</div>' +
                  '</div>{{editMode}}',
        scope: {
            fieldname: '@',
            placeHolder: '@',
            title: '@',
            editMode: '@',
            ngModel: '='
        }
    }

})

The form input is rendering correctly and everything else is working except the ng-show or ng-hide.

I have outputted the value of the editMode to check it is getting updated correctly and it is.

Any help will be greatly appreciated.

Many thanks Brent


Solution

  • Instead of using @, which passes profile_edit_mode as a string, use =, which will two way bind the actual value.

    <bos-input ... edit-mode="profile_edit_mode"></bos-input>
    

    Directive

    .directive('bosInput', function(){
        return {
            // Previous code...
            scope: {
                fieldname: '@',
                placeHolder: '@',
                title: '@',
                editMode: '=',
                ngModel: '='
            }
        }
    
    })
    

    This works because when you use @ and pass a string, 'false' still evaluates as truthy.