很抱歉,如果重复,但在StackOverflow的类似问题上找不到答案。
以下是代码:
http://plnkr.co/edit/IsdYMgcIznQ667ols67b?p=preview
我想要的是line 19
,我希望程序提醒我通过的号码,而目前它提醒我一个功能。该数字应为0
,1
或2
,具体取决于删除的哪一个条目(Remove Student)
。
答案 0 :(得分:1)
您的工厂方法接受两个参数index
和callback
。按此顺序。
调用它时,你只是传递一个函数。此功能接受index
和callback
。
相反,您需要传递index
和callback
,并接受data
。
$scope.removeStudent = function(index) {
console.log(index);
studentFactory.removeStudent(index, function(data){ // this is what's different
console.log(data);
});
};
答案 1 :(得分:0)
而不是:
myAppModule.factory('studentFactory', function (){ var students = [ {name: 'Mike', age: 34}, {name: 'John', age: 24}, {name: 'Trey', age: 24}]; var factory = {}; factory.getStudents = function (callback){ callback(students); } factory.removeStudent = function(index, callback) { alert(index); callback(students); } return factory; });
DO:
myAppModule.factory('studentFactory', function (){
var students = [
{name: 'Mike', age: 34},
{name: 'John', age: 24},
{name: 'Trey', age: 24}];
var factory = {};
factory.getStudents = function (){
//callback(students);
return students;
}
factory.removeStudent = function(index) {
students.splice(index, 1);
return students;
}
return factory;
});
然后在控制器中:
myAppModule.controller('studentsController', ['$scope', 'studentFactory', function ($scope, studentFactory){
$scope.students = [];
/*
studentFactory.getStudents(function (data){
$scope.students = data;
});*/
$scope.students = studentFactory.getStudents();
/*
$scope.removeStudent = function(index) {
console.log(index);
studentFactory.removeStudent(function (index, data){
console.log(data);
});
};*/
$scope.students = studentFactory.removeStudent(index);
}])
返回语句使代码变得更加简单。