Angular:将参数从Controller传递到Factory

时间:2017-02-04 00:45:28

标签: angularjs

很抱歉,如果重复,但在StackOverflow的类似问题上找不到答案。

以下是代码:

http://plnkr.co/edit/IsdYMgcIznQ667ols67b?p=preview

我想要的是line 19,我希望程序提醒我通过的号码,而目前它提醒我一个功能。该数字应为012,具体取决于删除的哪一个条目(Remove Student)

2 个答案:

答案 0 :(得分:1)

您的工厂方法接受两个参数indexcallback。按此顺序。

调用它时,你只是传递一个函数。此功能接受indexcallback

相反,您需要传递indexcallback,并接受data

      $scope.removeStudent = function(index) {
          console.log(index);
          studentFactory.removeStudent(index, function(data){ // this is what's different
              console.log(data);
          });
      };

答案 1 :(得分:0)

考虑使用return statements.

  

而不是:

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

返回语句使代码变得更加简单。