简体   繁体   中英

AngularJS - Pass Optional Parameter to Modal

How do I pass an OPTIONAL parameter to my angularJS modal? Here is my code:

CONTROLLER A (TRIGGER):

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

CONTROLLER B (MODAL):

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 :(
    }
  }
]);

NOTE: It works when i put preselectedAlbum as a dependency, but then i get the error whenever I don't explicitly pass it in. I want it to be optional instead.

Attach a value to the modal controller

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

Other than the resolve: , you could also pass values to the modal controller via scope: .

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

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

and then in the modal controller:

function uploadCtrl($scope, $modalInstance) {
  if ($scope.preselectedAlbum) {
    console.log('happy');
  } else {
    console.log('sad');
  }
}

Example plunker: http://plnkr.co/edit/ewbZa3I6xcrRWncPvDIi?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM