AngularJS: Which is better way to pass parameter to Modal Controller?

565 Views Asked by At

I have seen two ways of passing the parameters to the AngularJS Modal, one via resolve binding and another via scope binding. I was wondering if one is better than the other and why?

Resolve Binding

$modal.open({

      templateUrl: 'partials.html',
      controller: 'MyCtrl',
      resolve: {
         someData: function(){
             return 'Some Data';
         }
      }
})

.controller('MyCtrl',function(someData){

     console.log(someData); // prints Some Data
})

Scope Binding

var scope = $rootScope.$new();
scope.someData = 'Some Data';

$modal.open({

      templateUrl: 'partials.html',
      controller: 'MyCtrl',
      scope: scope
})

.controller('MyCtrl',function($scope){

     console.log($scope.someData); // prints Some Data
})
1

There are 1 best solutions below

0
KTU On

Resolve is not considered as binding in this case. When $modal.open it pass the value to the controller through resolve. Which means if you change the value in the parent controller, modal won't update unless it's re-initialize. However, You can pass in promises in resolve, which means if you are waiting for data coming back from server, using resolve can prevent modal loads before data come back.

resolve: {
  someData: function() {
    return $http.get('someurl');
  }
}

Pros & Cons

  • Run code asynchronously
  • Slower (if use promise)
  • Does not bind with parent scope value

Scope binding will allow you to have one-way binding data, whenever the data in the parent scope update, the value in the modal can update it's value simultaneously.

Pros & Cons

  • Faster
  • Binding with parent scope value
  • Might have scope pollution if you alter value in modal controller