2016-08-05 2 views
0

두 개의 레코드를 순차적으로 저장하려고하고 첫 번째 레코드의 id를 두 번째 레코드의 참조로 사용하려고합니다. 그래서 여기에 그것이 어떻게 생겼는지 ..

dept = {id: 1, name:"First"} 
student = {name: "a", dept_id: 1} 

이제 나는 새로운 부서를 선택하거나 만들 수있는 학생 양식을 가지고 있습니다. 내 컨트롤러이

.controller('StudentCtrl', ['$scope', 'Student', 'Department'], function($scope, Student, Department){ 

     $scope.saveStudent = function(){ 
      getDeptId($scope.deptName); 
      var o = new Student({ 
       name: $scope.name, 
       dept_id: $scope.deptId 
      }); 
     } 

     var getDeptId = function(name) { 
      index= _.findIndex($scope.depts, {name:name}) 
      if(index === -1) { 
      // new record 
      Department.save({name:name}, function(d){ 
      $scope.deptId= d["id"] 
      }) 
      } 
      else{ 
      //existing record 
      } 
     } 
}); 

처럼 보이지만 $ scope.deptId는 항상 null입니다.

나는 Angularjs의 초보자이며 어떤 도움을 주셔서 감사합니다. : D

답변

0

코드를 보면 Department.save가 아마도 비동기입니다.

다음과 같이 시도해 볼 수 있습니까?

.controller('StudentCtrl', ['$scope', 'Student', 'Department'], function($scope, Student, Department) { 

    $scope.saveStudent = function() { 
     // ** Pass a function as a promise for your getDeptId: 
     getDeptId($scope.deptName, function() { 
      var o = new Student({ 
       name: $scope.name, 
       dept_id: $scope.deptId 
      }); 
     }); 
    }; 

    var getDeptId = function(name, promise) { 
     index= _.findIndex($scope.depts, {name:name}); 
     if(index === -1) { 
     // new record 
     Department.save({name:name}, function(d){ 
      $scope.deptId= d["id"]; 

      // ** Call the promise only when you receive you "id": 
      promise(); 
     }); 
     } 
     else{ 
     //existing record 
     } 

    }; 
    }); 

나는 코드의 나머지 부분을 잘 모르겠지만, 난 당신이 내가 당신의 필요에 따라 생성이 "약속"을 호출해야합니다 생각합니다. dept_id를 설정할 때까지 "Department.save"가 서버에서 돌아올 때까지 기다려야한다는 것을 보여 드리고자합니다.

나는 초보자이기 때문에 테스트하지 않았습니다. 희망이 당신을 돕는다! :)