如何使用AngularJS访问工厂中的$ scope对象?

时间:2015-06-12 16:03:55

标签: javascript angularjs

我有帖子的序列化方法,所以riskAssessmentKey不是$scope.topRiskDTO的一部分,但我从$scope.riskAssessmentDTO.riskAssessmentkey传递riskAssessmentKey值,现在我发布到工厂但是当我保存所有值时是发布但风险评估关键未定义我不知道为什么..

到目前为止尝试过代码......

parentCtrl.js

$scope.addTopRisk = function(){
              topRiskGridConfig.topRiskmodalWinConfig.title = 'Add top Risk';
              $scope.viewTopRiskWin.setOptions(topRiskGridConfig.topRiskmodalWinConfig);
              $scope.$broadcast('addTopRisk',$scope.riskAssessmentDTO.riskAssessmentKey);
            };

childCtrl.js

$scope.topRiskDTO = {};
  $scope.issuePltDataSource = kendoCustomDataSource.getDropDownDataSource('RA_KY_CNCRN_IS_PLTFM');
  $scope.$on('addTopRisk', function (s,id){
    $scope.riskAssessmentDTO.riskAssessmentKey = id;
    $scope.viewTopRiskWin.open().center();
    $scope.submit = function(){
      rcsaAssessmentFactory.saveTopRisk($scope.topRiskDTO,id).then(function(){
        $scope.viewTopRiskWin.close();
      });
    };
  });

factory.js

   var serializeTopRisk = function (topRisk,id) {
          var riskAssessmentKey = id;
          var objToReturn = {
              topRiskName: topRisk.topRiskName,
              mitigationActivityDes: topRisk.mitigationActivityDes,
              issuePltfLookUpCode: topRisk.issuePltfLookUpCode,
              issueNo: topRisk.issueNo,
              riskAssessmentKey: topRisk.riskAssessmentKey
          };

          if(topRisk.riskAssessmentKey){
            objToReturn.riskAssessmentKey = topRisk.riskAssessmentKey;
          }
          return objToReturn;
      };
         saveTopRisk: function(topRisk,id) {
                      var request = serializeTopRisk(topRisk);
                      console.log('request payload', JSON.stringify(request));
                      console.log('ID :: ', id);
                      var endpoint = 'app/assessment/rest/addTopRisks';
                      return $http.post(endpoint, request);


 }

1 个答案:

答案 0 :(得分:2)

您忘记将id传递给serializeTopRisk函数。

所以你已经正确地传递了params:

saveTopRisk: function(topRisk,id) {
                  var request = serializeTopRisk(topRisk);

但是serializeTopRisk也应该得到id

var serializeTopRisk = function (topRisk, id) { // added the id over what you originally had
          var riskAssessmentKey = $rootScope.riskAssessmentDTO.riskAssessmentKey; // drop this, use id instead

如果您不需要,请不要使用rootScope在工厂和控制器之间传递数据(看起来您已经通过向控制器提供对象输入将值传递给工厂,保持这种方式并从工厂中删除rootScope用法)。