S
S
Sergey Gladyshev2016-10-29 05:08:14
JavaScript
Sergey Gladyshev, 2016-10-29 05:08:14

Angular. Directives for dynamically added elements do not work.?

Good day.
There is such a code.

var left_elements = angular.element(document.querySelector("body"));
var left_elementsE = left_elements.find('.js-content_left__elements');				
var newLi = angular.element("<li>");
var newA = angular.element("<a>");
newA.attr("href", "#");
var newSpan = angular.element("<span>");
newSpan.addClass("glyphicon");
newSpan.addClass("glyphicon-remove");
newSpan.addClass("pull-right");
var newNumber=$("ul").find($("li")).length;
newSpan.attr("data-id", newNumber+1);
newSpan.attr("ng-click", "ngDelete("+(newNumber+1)+");");
            
left_elementsE.append(newLi);
newLi.append(newA);	

newA.append($scope.blur);
newA.append(newSpan);

As a result, one more li element is added to the list of li elements
<li>
<a href="#">111<span class="glyphicon glyphicon-remove pull-right" data-id="4" ng-click="ngDelete(4);"></span>
</a>
</li>

But ngDelete on this dynamically created element does not work.
I know that in this case you need to use $compile, but I'm still new to Angular, so please poke your nose at an example solution for my case...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nicholas, 2016-10-29
@healqq

https://docs.angularjs.org/api/ng/service/$compile
If in simple terms - you need to inject $compile and call it on new elements, you can before adding it to the DOM.
ps for a list, you almost never need to add elements by hand. Get an array of elements and output it through ng-repeat.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question