Jeremy Moritz
Jeremy Moritz

Reputation: 14922

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.

Upvotes: 5

Views: 5219

Answers (2)

Steve
Steve

Reputation: 387

Attach a value to the modal controller

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

Upvotes: 6

runTarm
runTarm

Reputation: 11547

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

Upvotes: 5

Related Questions