为什么我得到未定义

时间:2015-07-28 13:23:41

标签: javascript angularjs twitter-bootstrap bootstrap-modal

我的应用程序包含一个模态,我在其中发送变量调用index。我可以在代码的某些部分完美地访问这个变量,但在关闭模态之后,我的变量变得不确定。为什么会这样?

$scope.novoCampo = function (index) {
    //Works
    console.log(index);
    var modalInstance = $modal.open({
      animation: $scope.animationsEnabled,
      templateUrl: 'myModalContent.html',
      controller: 'ModalInstanceCtrl',
      size: '',
      resolve: {
        index:  function () {
          return index
        }
      }
    });

    modalInstance.result.then(function (nomeCampo, index) {
      //I can access 'nomeCampo' but 'index' is undefined 
      console.log(nomeCampo + '\t' + index);
    }, function () {
      $log.info('Modal dismissed at: ' + new Date());
    });
  };

  $scope.toggleAnimation = function () {
    $scope.animationsEnabled = !$scope.animationsEnabled;
  };

模态控制器

oknok.controller('ModalInstanceCtrl', function ($scope, $modalInstance, contatosAPI, index){
  $scope.animationsEnabled = true;

  $scope.ok = function () {
    //Works
    console.log('index ' + index);
    $modalInstance.close($scope.nomeCampo, index);
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };

});

1 个答案:

答案 0 :(得分:3)

您不能将两个项目返回到承诺,只需返回一个包含您需要的所有内容的对象,例如:

$modalInstance.close({nomeCampo: $scope.nomeCampo, index: index});

然后在你的控制器中:

modalInstance.result.then(function (result) {
  console.log(result.nomeCampo + '\t' + result.index);
},