![](/img/trans.png)
[英]AngularJS ng-click() is not working in dynamic call by .append(' ') function in controller
[英]ng-click not working when using append function
我試圖在創建動態元素時使用ng-click
調用函數但到目前為止沒有成功。 這是我的代碼
$scope.myfunc = function(){
alert("anything")
}
var divtoappend=angular.element( document.querySelector('#slist'));
divtoappend.append("<button class = 'optv' ng-click='myfunc()'>" +mybutton+ "</button>");
...
沒有錯誤,點擊時沒有任何反應
您需要編譯動態生成的HTML,以便它在AngularJS的范圍內。 只需編譯內部追加方法即可
divtoappend.append($compile("<button class = 'optv' ng-click='myfunc()'>" +mybutton+ "</button>")($scope));
在此之前,在您的控制器中注入$compile
。
我創建了一個plunkr看到這個plunkr鏈接
在注入DOM樹之前,你必須使用$compile
API編譯DOM,如下所示。
divtoappend.append($compile("<button class = 'optv' ng-click='myfunc()'>" +mybutton+ "</button>")($scope));
通過編譯DOM angular,將所有HTML級別綁定放在$scope
$$watchers
數組中,以確保UI在每個摘要周期都是最新的。
您需要使用$ compile編譯DOM元素,如下所示
$compile(divtoappent)(scope);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.