我正在尝试使用 ng-repeat
动态添加数据。我不知道为什么它没有添加。我输入在数据中动态添加的“名称”,但它没有显示在用户界面中。这是demo
app.controller("studentcntr", ['$scope', function(scope) {
scope.studentDetail = [];
var student = {
name: ''
};
scope.addStudent = function() {
bootbox.prompt("Enter Name!", function(res){
if (res == null) {
} else {
student.name = res;
scope.studentDetail.push(student);
}
});
};
}])
最佳答案
这一行
scope.studentDetail.push(student);
在 Angular 之外执行,因此 Angular 不知道 StudentDetail 已经更改。您可以使用scope.$apply()来要求Angular检查更改
scope.$apply(function() {
scope.studentDetail.push({
name: res
});
});
代码的另一个问题是您在 Controller 内声明了一个变量 Student。所以每次你将它推送到scope.studentDetail中时,你实际上是再次推送同一个对象,这将导致ng-repeat错误。我更改了上面的代码以每次推送新对象
关于javascript - 为什么元素没有以 Angular 动态添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25172572/