1

I searched on this issue too much here on stackoverflow, there were similar ones but none helpful and tried almost everything. The problem is :

I have an application in which I am using angular js to bind events like load more(pagination),"add to cart" etc etc .

I am not using routes to load templates. It is simply a grails application with ng-app in gsp and I am rendering template from server on ajax $http request.

When the page is loaded first time, view with model(data) is coming at once, so events are just working fine. But when I "load more" data with $http service and append to current DOM, event binding does not work. Even jquery click events are not working .

I am using this to bind data :

$('#itemsSpace').append($compile(response.data)($scope));

if(!$scope.$$phase) {
    $scope.$apply() 
}

Where response is server response with html data.

Any guesses ? Any more explanations needed ?

Thanks!

rrk
  • 15,677
  • 4
  • 29
  • 45
89n3ur0n
  • 921
  • 11
  • 24
  • do you bind to click events using ng-click directive or jquery .on() methods? – Prashant Jan 19 '16 at 18:44
  • currently they are with ng-click directive and I want to work with only that as too many frameworks will just make mess . After appending html to current dom, ng-click does not work. – 89n3ur0n Jan 19 '16 at 18:46
  • You need to append to the DOM first and then compile the DOM with the $scope. – Prashant Jan 19 '16 at 18:47
  • Tip: don't do `if(!$scope.$$phase)`. It's bad. Use $timeout(function(){$scope.$apply()})` instead. (http://stackoverflow.com/questions/22346990/why-is-using-ifscope-phase-scope-apply-an-anti-pattern) – akn Jan 19 '16 at 18:51
  • Something like this `$('#itemsSpace').append(response.data); var doc = document.getElementById('itemsSpace'); $compile(doc)($scope) $timeout(function(){$scope.$apply()})` . I did not work. – 89n3ur0n Jan 19 '16 at 18:52

1 Answers1

1
var $items = $(response.data);
$('#itemsSpace').append($items);

$compile($items)($scope);

EDIT:

Looking into the source of $compile, the compiler converts the given node into jQLite object if the node is not a jQLite instance. So, the OP's original code would work just as much as the code here. Example. The problem therefore lies somewhere else.

Prashant
  • 7,340
  • 2
  • 25
  • 24
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – ryanyuyu Jan 19 '16 at 20:06
  • but still events are not binding , not sure why if above way is the right way of doing so. – 89n3ur0n Jan 20 '16 at 07:33
  • is there any way I can help with explanation ? – 89n3ur0n Jan 20 '16 at 14:50
  • I just looked into it once again with fresh mid, problem was due to parent - child controllers . My bad, load more was in parent controller and click was in child controller. binding scope to same controller where the click event is, fixed problem. – 89n3ur0n Jan 20 '16 at 15:01