I am trying to add data dynamically using ng-repeat. I don't know why it is not adding. I enter "name" which is added dynamically in the data, but it is not showing in the UI. Here is a 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);
}
});
};
}])
This line
scope.studentDetail.push(student);
is executed outside of angular, so angular doesn't know that studentDetail is already changed. You can use scope.$apply() to ask angular to check for changes
scope.$apply(function() {
scope.studentDetail.push({
name: res
});
});
Another issue with your code is that you declare a variable student inside the controller. So every time you push it inside scope.studentDetail, you are actually pushing the same object again, which will cause error in ng-repeat. I changed in the above code to push new object every time
bootbox is an external library, it is not aware that angularjs has digest cycles to keep the view up to date.
Just modify your code like this:
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
});
};
To avoid you to come back later with another question you have to create an object each time for student inside your bootbox's callback function scope to avoid pushing several times the same object in your studentDetail array.
As a result your final code could look like this:
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
});
};
}]);