我只发布必要的代码,解决这么多问题将消除我的其余疑虑。我是 angularjs 的新手,所以如果我问一些愚蠢的问题,请原谅。
我正在使用 ng-repeat 生成一个列表,该列表使用 Controller 范围中定义的数组。当我单击“添加另一个”按钮时,将创建一个新元素。我想访问该元素以向其添加一个类。但是当我在同一函数“addNewForm”中使用“getElementById”函数时,我得到“null”。 但是,当我通过点击“Find Untitled”按钮调用函数“fn”时,我得到了正确的元素。有人能解释并解决这个问题吗?任何帮助表示赞赏。提前致谢!
我发布以下代码:
HTML:
<div ng-controller="myctrl3">
<ul id ="menu_Ul">
<li ng-repeat="x in list">
<button id="{{ 'navAppsButtonID-' + $index }}">{{x}}</button>
<br>
</li>
<li>
<button ng-click="addNewForm()">Add another</button>
</li>
</ul>
<button ng-click="fn()">Find Untitled</button>
</div>
JS:
.controller("myctrl3", function($scope) {
var list = ['abcd', 'efgh', 'ijkl', 'mnop'];
$scope.list = list;
$scope.abc = function () {
var listPush = function () {
$scope.list.push("Untitled Menu");
for(var i = 0;i<$scope.list.length-1;i++) {
var element = document.getElementById('navAppsButtonID-'+i);
element.classList.remove('current');
}
};
var listLen = $scope.list.length;
if($scope.list[listLen-1] === undefined) {
listPush();
}
else if ($scope.list[listLen-1] == "Untitled Menu") {
alert("Cannot open more than one Untitled Menu at the same time.");
}
else {
listPush();
}
};
$scope.addNewForm = function() {
$scope.abc();
console.log("Element is: ", document.getElementById('navAppsButtonID-'+($scope.list.length-1)));
};
$scope.fn = function () {
console.log("Element is: ", document.getElementById('navAppsButtonID-'+($scope.list.length-1)));
};
})
最佳答案
你想太多 jQuery 而太少考虑 Angular。如果目标是将类添加到 ng-repeat 的最后一个元素,则可以这样做:
<li ng-repeat="x in list">
<button ng-class="{ current: $last }">{{ x }}</button>
</li>
$last
是 ng-repeat
内可用的变量,如果这是真的,ng-class
将在元素上设置类current
。
在 Angular 中工作时,您不会从其他地方为 getElementById
的元素分配唯一的 id。
关于javascript - 如何通过AngularJS中的ng-repeat动态创建的id获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52386535/