【发布时间】:2015-12-31 22:24:25
【问题描述】:
我正在动态添加 Li 元素,其中我附加了作用域函数。但是当我点击它时,它会被多次调用。 请在我遇到此问题的地方查看此小提琴演示。 http://jsfiddle.net/udmcv/260/
Html如下
<div style="border:solid;color:red;Margin-bottom:4px;">
Click on Create Button to Generate the required li'sThe issue is that when there multiple Li the corresponding is getting called multiple time
<ul id="ulTabList" >
</ul>
</div>
<div style="margin-top:10px;">
<input type="button" ng-click="Addli()" value="Create"/>
</div>
下面是我正在使用的 Angular 代码
var app = angular.module('my-app', [], function () {
})
app.controller('AppController', function ($scope, $compile) {
var workGroupTab ="TestA"
$scope.Addli =function(){
var el = $("#ulTabList").append('<li ng-click="OpenWorkGroupTab();">Text of Li</li>'
+'<input id="btnClose_4341" type="button" value="btn" style="margin-left:1px;" ng-click="fn_btnClose()">');
$compile(el.contents())($scope);
}
$scope.fn_btnClose = function(){
console.log('clicked'+ 'val');
}
$scope.OpenWorkGroupTab =function(){
console.log('val2');
}
})
我还看到了一些帖子,其中提出了一些建议,但对我不起作用。 问题就像假设当我生成 3 li 然后单击第一个 Li 按钮时,它会被调用 3 次。 当我点击 2nd Li 按钮时,它会被调用 2 次,依此类推。
请为这个问题提出一些想法。 谢谢!
【问题讨论】:
-
你为什么不使用
ng-repeat??? -
不要像这样手动添加到 DOM。您应该操作绑定到视图的数据结构以创建您想要的...而不是手动操作视图。
-
@Grundy :实际上我希望仅在单击按钮时生成 li 元素并将其附加到 Ul
-
将
ng-repeat与范围数组一起使用。 -
@rahulrathore,所以只需在按钮单击时在数组中添加元素