为什么元素不是dynamic添加在angular

我正在尝试使用ng-repeatdynamic添加数据。 我不知道为什么不加。 我input数据中dynamic添加的“名称”,但不显示在用户界面中。 这里是一个演示

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

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

可选的

为了避免以后再回到另一个问题,您必须每次为student在您的bootbox的callback函数范围内创build一个对象,以避免在您的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 }); }; }]); 

这条线

 scope.studentDetail.push(student); 

在angular度以外执行,所以angular度不知道studentDetail已经改变。 你可以使用scope。$ apply()来询问angular度来检查更改

 scope.$apply(function() { scope.studentDetail.push({ name: res }); }); 

你的代码的另一个问题是你在控制器里声明一个variables学生。 所以每当你把它推入scope.studentDetail,你实际上是再次推动相同的对象,这将导致错误重复。 我改变了上面的代码,每次推新对象