最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论