3
$scope.addNew = function(){    
    $('.thumb-img-gallary').append("<li><span class='img-del' ng-click='delThumbImgGallaryPhoto($event)'>X</span><img class='thumb-img' src='data:image/jpeg;base64,"+imageData+"'/></li>");    
}

I am calling this function to add element dynamically. But then delThumbImgGallaryPhoto() is not getting called.

1

3 Answers 3

6

you cannot just append an element with a ng-click or any other directive, and expect it to work. it has got to be compiled by angular.

explenation about compilation from angular docs:

For AngularJS, "compilation" means attaching directives to the HTML to make it interactive

compelation happens in one of two cases:

  • When Angular bootstraps your application, the HTML compiler traverses the DOM matching directives against the DOM elements

  • when you call the $compile service inside an angular context

so what you need to do, is first to compile it(remeber to inject the $compile service in your controller), and then append it:

$scope.addNew = function(){    
    var elem = $compile("<li><span class='img-del' ng-click='delThumbImgGallaryPhoto($event)'>X</span><img class='thumb-img' src='data:image/jpeg;base64,"+imageData+"'/></li>")($scope);
    $('.thumb-img-gallary').append(elem);    
}

BTW, remember it is prefable not to have any DOM manipulations done in the controller. angular has directives for that.

3

You have to compile it with scope

try like this

var item="<li><span class='img-del' ng-click='delThumbImgGallaryPhoto($event)'>X</span><img class='thumb-img' src='data:image/jpeg;base64,"+imageData+"'/></li>"
 $('.thumb-img-gallary').append(item);
$compile(item)($scope);
3

angular doesn't know anything about your newly added element. You need to compile your newly added element using $compile. and you should better use directive for this task.

It is a bad habit to access ui elements from controller.

edit: it would be best using ng-repeat for this task. lets say you have a thumb-gallery directive which is repeated using ng-repeat by thumbs array.

when you need to add a new image you only need to add it to your thumbs array. it is simple and straightforward

Your html would look like

 <thumb-gallery ng-repeat="gallery in galleries"></thumb-gallery>

and your js would look like

 var gallery = {};
 $scope.galleries.add(gallery);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.