如何从函数中访问变量

时间:2016-12-14 18:07:01

标签: javascript angularjs angularjs-scope

我需要

batchdata:{course_name:"xyz",batch_fees:"1200",---,course_id:"xyz123"}

要发送数据库,但我发送course_id以及 batchData 时遇到问题,因为我从其他服务中获取course_id课程表所以请查看我没有访问此代码的代码 - > response.data.data[0]._id因为我无法在函数外部访问它,因为它是局部变量所以有任何方式可以将course_id batchData 对象绑定...

  app.controller('batch_add', function($scope, $http) {
        $http.get("/courses/getall")
        .then(function(response) {
                if (response.data.length == 0) {
                    $scope.items = [{ course_name: "No data", course_desc: "No data", course_fees: "No data" }];
                } else {
                    $scope.items = response.data.data;
                    var course_name_items = []
                    for (var i = 0; i < $scope.items.length; i++) {
                      course_name_items.push($scope.items[i].course_name)
                    }
                    $scope.course_items = course_name_items;
                }
            });

        $scope.batch_status_items = ['Pending', 'Running', 'Finished', 'Canceled' ]



      $scope.batchData={};
      $scope.login =  {"batchData" : $scope.batchData};
      $scope.submitForm = function() {
      $scope.login =  {"batchData" : $scope.batchData};
      $scope.fail = false;
          $http({
              method  : 'POST',
              url: 'batches/add',
              data    : $scope.login
      })
          .success(function(data) {
              if (data.success == true) {
                  $scope.fail = true;
                  $scope.success = true;
                  $scope.success_message = data.message;
                  var courseName = $scope.batchData.course_name;
                  $http.get("/courses/search/"+courseName)
                  .then(function(response) {
                          if (response.data.length == 0) {
                            console.log("error");
                          } else {
                              $scope.batchData.course_id= response.data.data[0]._id

                          }
                      });
                          toastr.options = {"positionClass": "toast-bottom-right"}
                          Command: toastr["success"]("A new batch has been added!")
                  } else {
                      $scope.fail = true;
                      $scope.success = false;
                      $scope.error_message = data.message;
                      console.log($scope.success_message);
                     //  toastr.error('Something went wrong.', 'Ooops!')
                  }                      
            });
  $scope.batchData.course_id = response.data.data[0]._id
          };
      });

1 个答案:

答案 0 :(得分:0)

为什么不首先获得course_id,然后将该id与batchData一起发送到数据库?