WordPress opening media library from Angular JS function (ng-click)

I am programming a plugin and I need to select an image. I have done the correct code to call the media library window. But when I click the button and select an image from the media library, nothing happens. If I click again, the first image url selected appears in the textbox.

Here is my HTML code:

Read More
<div class="uploader">
    <input id="library_image" name="settings[library_image]" ng-model="imagenAd" disabled type="text" />
    <button id="open_library" ng-click="open_media_library()" class="button" name="open_library">Seleccionar</button>
</div>

And there is the controller code:

$scope.imagenAd = '';
var selURL = '';
var window = wp.media({
    title: 'Seleccione una imagen para el anuncio',
    library: {type: 'image'},
    multiple: false,
    button: {text: 'Insert'}
});

// Function used for the image selection and media manager closing
var gk_media_set_image = function() {
  var selection = window.state().get('selection');

  // no selection
  if (!selection) {
      return;
  }

  // iterate through selected elements
  selection.each(function(attachment) {
      var url = attachment.attributes.url;
      //alert(url);
      selURL = url;
  });
};

// closing event for media manger
window.on('close', gk_media_set_image);
// image selection event
window.on('select', gk_media_set_image);

$scope.open_media_library = function(obj, $event){
    window.open();
    $scope.imagenAd = selURL;
  }

What I am doing wrong? Thanks

Related posts

4 comments

  1. I have replaced your open_media_library function, then it worked for me.

    $scope.open_media_library = function(obj, $event){
      window.open();
       setTimeout(function() {
        $scope.imagenAd = selURL;
        $scope.$apply(); //this triggers a $digest
      }, 2000);
    
    }
    
  2. I never used Angular JS but i can easily give you answer using jquery.

    But only if you don’t have to use Angular.

  3. SOLVED:
    Because selURL variable was modified outside angular world, Angular could only apply his value on each digest cycle. So on every call of the window we need to force digest with:
    $angular.$digest();

Comments are closed.