Search code examples
angularjsangular-ng-if

dynamic variable inside ngif not working


I have a piece of code like this

ng-show="!edit{{id}} && imageUrl"

But this does not seem to work. Where as

ng-show="!edit1 && imageUrl" 

works. Is there any problem in syntax??

Actual Piece of code

template: '<div id="dropTarget{{imageid}}" ng-show="edit{{imageid}}">'+
            '<img id="imageView{{imageid}}" ng-src="{{imageUrl}}" />'+
        '</div>'+
        '<img id="imageView{{imageid}}" ng-if="!edit{{imageid}} && imageUrl" ng-src="{{imageUrl}}" alt="Coach"/>'+
        '<div class="my-new-photo" ng-if="!edit{{imageid}} && !imageUrl">+</div>'+
        '<span class="edit-info" ng-click="showUploadImageOptions(imageid)" ng-show="!edit{{imageid}} && imageUrl">EDIT</span>'+
        '<span class="edit-info" ng-click="showUploadImageOptions(imageid)" ng-show="!edit{{imageid}} && !imageUrl">NEW</span>'+
            '<div ng-show="edit1" class="buttons-section">'+
                '<form enctype="multipart/form-data" method="post">'+
                    '<input type="file" name="filesToUpload{{imageid}}" id="filesToUpload{{imageid}}" style="display:none;"/>'+
                    '<span class="upl-sav-can" ng-click="uploadImage(imageid)">Browse</span>'+
                    '<span  class="upl-sav-can" ng-click="revertImage(imageid)">Cancel</span>'+
                '</form>'+
            '</div>',

Solution

  • ngShow expects Angular expression which is kind of regular javascript expression (with certain limitations). So think of what you write in these cases, as normal javascript expression.

    Now ask yourself: is !edit{{id}} && imageUrl valid javascript expression (code)? Of course, no. Angular throws an error when provided expression cannot be parsed and evaluated ($parse service does this) as valid javascript code.

    However

    ng-show="!edit[id] && imageUrl" 
    

    would be valid expression using bracket notation to access variable property of the object/array. This is what you need to use in this case.