AngularJS - 将可选参数传递给模态框

5

如何向我的AngularJS模态框传递可选参数?以下是我的代码:

控制器A(触发器):

$modal.open({
  templateUrl: 'UploadPartial.html',
  controller: 'photos.uploadCtrl',
  resolve: {
    preselectedAlbum: function preselectedAlbum() {
      return angular.copy($scope.selectedAlbum);
    }
  }
});

控制器 B (模态框):

app.controller('photos.uploadCtrl', [
  '$scope',
  '$modalInstance',
  '$injector',
  function uploadCtrl($scope, $modalInstance, $injector) {
    if ($injector.has('preselectedAlbum')) {
      console.log('happy');  // I want this to work, but $injector doesn't find it
    } else {
      console.log('sad');  //  Always gets here instead :(
    }
  }
]);

注意:当我将preselectedAlbum作为依赖项时,它可以工作,但是当我不明确传递它时,就会出现错误。我希望它是可选的。


1
我认为这是不可能的,注入的$injector服务对resolve:对象一无所知。当它不需要时,你可能需要传递一个虚拟函数。或者改变传递preselectedAlbum的方式,也许通过$scope对象。 - runTarm
@runTarm,您能否展示一下如何通过$scope对象将信息传递给控制器?如果可能的话,这对我来说非常完美,但我不知道如何进行更改以使其在新打开的控制器中持久存在。 - Jeremy Moritz
2个回答

6

为模态控制器附加一个值

angular.module('app')
    .controller('TestCtrl',TestCtrl)
    .value('noteId', null); // optional param

这怎么被投票为正确答案的?打开模态框时,不使用上述流畅类型语法来定义它。控制器只是传递给$modal.open()选项的属性;即你不需要调用module.controller(),所以.value不可用。我猜如果控制器作为你的模块的一部分注册了,那么你可能能够使用.controller(...).value,但我怀疑此时你想要的值并没有准备好。 - jessewolfe

5

除了使用resolve:,您还可以通过scope:向模态控制器传递值。

$scope.preselectedAlbum = angular.copy($scope.selectedAlbum);

$modal.open({
  templateUrl: 'UploadPartial.html',
  controller: 'photos.uploadCtrl',
  scope: $scope,
});

然后在模态控制器中:

function uploadCtrl($scope, $modalInstance) {
  if ($scope.preselectedAlbum) {
    console.log('happy');
  } else {
    console.log('sad');
  }
}
示例 Plunker:http://plnkr.co/edit/ewbZa3I6xcrRWncPvDIi?p=preview

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接