javascript - ng-click not working when using append function - Stack Overflow

I am trying to call a function using ng-click when dynamical elements are created but with no success s

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. like divtoappend.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
Add a ment  | 

4 Answers 4

Reset to default 4

You 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'>&times;</button></div>")($this.$scope));

where: '#groupList' is the div that will receive the other div

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742276255a4413647.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信