3

I'm using AngularUI modal in my app. Modal contains input field that is pre populated with some value. Request: When modal opens, text in that input field should be selected.

I have made directive for selected text input and furthest I got is selecting all text when input is clicked according to this answer, which is fine but I need that functionality when modal is opened.

I have seen in other thread that modal instance has "opened" promise but inside that block I can't access the input.

Modal dialog:

var modalInstance = $modal.open({

templateUrl: 'app/main/templates/dialogs/share-dialog.tpl.html',
controller: function ModalCtrl($scope, $modalInstance, item) {

    $scope.ok = function () {

        $modalInstance.dismiss('cancel');
    };

    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };

},
resolve: {
    item: function () {
        return item;
    }
}
});

Template part with select directive:

<input ng-model="shareLink" type="text" class="form-control" id="share" selected-text >

Selected text directive:

var SelectedText = function () {
    return {
        restrict: 'A',
        link: function(scope, element, attrs){
            element.on('click', function () {
                this.select();
            });
        }
    };
};

return SelectedText;
Community
  • 1
  • 1
NenadPavlov
  • 217
  • 1
  • 2
  • 10

1 Answers1

1

I think the following directive will solve your problem:

app.directive("selectImmediately", function($timeout) {
  return {
    restrict: "A",
    link: function(scope, iElement) {
      $timeout(function() { // Using timeout to let template to be appended to DOM prior to select action.
        iElement[0].select()
     });
    }
  }
});

Usage:

<input ng-model="name" type="text" class="form-control" id="share" select-immediately >

Full example in plnkr can be seen here. You can use this directive anywhere.

Umut Benzer
  • 3,476
  • 4
  • 36
  • 53