I am trying to call a function using ng-click
when dynamical elements are created but with no success so far. Here is my code
$scope.myfunc = function(){
alert("anything")
}
var divtoappend=angular.element( document.querySelector('#slist'));
divtoappend.append("<button class = 'optv' ng-click='myfunc()'>" +mybutton+ "</button>");
...
No error is thrown and nothing happens on click
I am trying to call a function using ng-click
when dynamical elements are created but with no success so far. Here is my code
$scope.myfunc = function(){
alert("anything")
}
var divtoappend=angular.element( document.querySelector('#slist'));
divtoappend.append("<button class = 'optv' ng-click='myfunc()'>" +mybutton+ "</button>");
...
No error is thrown and nothing happens on click
Share Improve this question edited Jan 9, 2017 at 11:39 sam asked Jan 9, 2017 at 11:31 samsam 6982 gold badges13 silver badges36 bronze badges 3-
5
pile a DOM with
$scope
before injecting it in DOM tree. likedivtoappend.append($pile("<button class = 'optv' ng-click='myfunc()'>" +mybutton+ "</button>")($scope));
– Pankaj Parkar Commented Jan 9, 2017 at 11:32 -
as @PankajParkar said also inject
$pile
service. – Hadi Commented Jan 9, 2017 at 11:34 - Thanks @PankajParkar You should post this as an answer so that I can verify it and other may find this helpful – sam Commented Jan 9, 2017 at 11:38
4 Answers
Reset to default 4You have to pile DOM with $pile
API, before injecting into DOM tree, like below.
divtoappend.append($pile("<button class = 'optv' ng-click='myfunc()'>" +mybutton+ "</button>")($scope));
By piling DOM angular will put all HTML level bindings in $$watchers
array of $scope
to make sure UI is up to date on every digest cycle.
You need to pile the dynamically generated HTML so that it is under the scope of AngularJS. Just pile inside append method like
divtoappend.append($pile("<button class = 'optv' ng-click='myfunc()'>" +mybutton+ "</button>")($scope));
Before this inject $pile
in your controller.
I have created a plunkr see this plunkr link
You need to pile your DOM elements as follow using $pile
$pile(divtoappent)(scope);
After inject {$pile} you can do:
angular.element('#groupList').append($this.$pile("<div id='Somevalue'> divText <button type='button' class='close' ng-click='yourFunctionHere'>×</button></div>")($this.$scope));
where: '#groupList'
is the div that will receive the other div