为什么元素不是在angular中动态添加的?

why element is not added in dynamically in angular

本文关键字:动态 添加 angular 元素 为什么      更新时间:2023-09-26

我正在尝试使用ng-repeat动态添加数据。我不知道为什么不加。我输入"name",这是在数据中动态添加的,但它没有显示在UI中。下面是一个示例

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
    });
});

代码的另一个问题是,您在控制器内部声明了一个变量student。所以每次你把它推到作用域中。studentDetail,你实际上再次推送同一个对象,这会在ng-repeat中导致错误。我在上面的代码中修改为每次

push新对象

bootbox是一个外部库,它不知道angularjs有消化循环来保持视图的更新。

这里的

plunkr

就像这样修改你的代码:

scope.addStudent=function(){
        bootbox.prompt("Enter Name!",function(res){
            if(res==null){
            }else {
                student.name=res;
                scope.studentDetail.push(student);
            }
            scope.$digest(); // here is the new line to update models
        });

    };

可选

为了避免你以后再回来问另一个问题,你必须在bootbox的回调函数范围内每次为student创建一个对象,以避免在studentDetail数组中多次推送相同的对象。

因此,您的最终代码可能看起来像这样:
app.controller("studentcntr",['$scope',function(scope){
    scope.studentDetail=[];
    // I removed var student
    scope.addStudent=function(){
        bootbox.prompt("Enter Name!",function(res){
            if (res == null) {
            } else {
                scope.studentDetail.push({ name: res });
            }
            scope.$digest(); // here is the new line to update models
        });
    };
}]);