Hacker
Hacker

Reputation: 7906

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>',

Upvotes: 3

Views: 13423

Answers (3)

Lucas
Lucas

Reputation: 10303

Why not make the right thing and call a method for that return value?

Partial code:

<span class="edit-info" ng-click="showUploadImageOptions(imageid)" ng-show="returnEditId(imageid) && imageUrl">EDIT</span>

JS:

    $scope.returnEditId = function(id){
        if(!$scope.edit[id])
         return false;
        else
         return true;
    }

Upvotes: 0

Anid Monsur
Anid Monsur

Reputation: 4538

What you're trying to do is not possible. As @dfsq said, ngShow expects Angular expression. You can't access a scope variable by interpolating its name in an Angular expression.

Your best options are to make edit an array or an object, and then access it's contents via index or key.

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

Upvotes: 2

dfsq
dfsq

Reputation: 193261

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.

Upvotes: 2

Related Questions