Reputation: 4282
Sorry if duplicate, but really couldn't find the answer at similar issues here at StackOverflow.
Here's the code:
http://plnkr.co/edit/IsdYMgcIznQ667ols67b?p=preview
What I want is in line 19
, I want the program to alert the number I pass, while currently it alerts me a function. The number should be either 0
, 1
, or 2
, depending on which one entry removed (Remove Student)
.
Upvotes: 0
Views: 47
Reputation: 48968
Consider using return statements.
Instead of:
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;
});
Then in the controller:
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);
}])
Return statements make the code so much simpler.
Upvotes: 0
Reputation: 1803
Your factory method accepts two parameters, index
and callback
. In that order.
When calling it, you're only passing it a function. This function accepts index
and callback
.
Instead, you need to pass it an index
and a callback
which accepts data
.
$scope.removeStudent = function(index) {
console.log(index);
studentFactory.removeStudent(index, function(data){ // this is what's different
console.log(data);
});
};
Upvotes: 1