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.

Manish Kumar
  • 10,214
  • 25
  • 77
  • 147
  • why are you inserting html with jQuery in the first place and not updating your data model instead? Suggested reading: [thinking-in-angularjs-if-i-have-a-jquery-background](http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background) – charlietfl Sep 18 '15 at 10:06

3 Answers3

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.

MoLow
  • 3,056
  • 2
  • 21
  • 41
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);
bahadir
  • 709
  • 1
  • 11
  • 28
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);
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80