AngularJS: Where is the code that updates the form field after the promise is resolved?

In my AngularJS application, I have a template containing a button <textarea>and a submit button. A <div>(which could just as easily be <form>) wraps both of these elements and has a controller. The controller uses $ resource to POSTvalue from <textarea>in the REST API when the submit button is clicked.

Template:

<div ng-controller="MyController as vm">
  <textarea ng-model="vm.text" rows="5"></textarea>
  <button ng-click="vm.save()">Save</button>
</div>

Controller:

angular.module('myApp')
  .controller('MyController', MyController);

MyController.$inject = ['myRestApiResource'];

function MyController(myRestApiResource) {
  var vm = this;
  vm.save = function() {
    var params = [];
    var postData = {text: vm.text};
    myRestApiResource.save(params, postData)
      .then(function(res) { /* success handler */ })
      .catch(function(res) { /* error handler */ });
  };
}

When the save() $ prom resource method is rejected, the response data (in some cases) contains a property error.positionthat refers to the index of the row where the syntax error was detected at vm.text.

<textarea> error.position - . , .

:

, <textarea> ( ), ...

  • ​​
  • -

... ?

.

, , DOM... $element ( jQuery) .

, , . , Angular Best Practices $broadcast $on ", ".

, , - -, !: -)

!


, , @kristin-fritsch:

angular.module('myApp')
  .directive('selectionRange', selectionRangeDirective);

function selectionRangeDirective() {
  return {
    restrict: 'A',
    scope: {
      selectionRange: '='
    },
    link: function(scope, iElement) {
      var element = iElement[0];
      if (element.setSelectionRange && typeof element.setSelectionRange === 'function') {
        scope.$watch('selectionRange', function(range) {
          if (range && typeof range.start === 'number' && range.start > -1 && range.start < iElement.val().length) {
            element.focus();
            element.setSelectionRange(range.start, range.end);
          }
        });
      }
    }
  };
}

, :

<textarea ng-model="vm.text" rows="5" selection-range="vm.selection"></textarea>

... vm.selection start end , .

myRestApiResource.save(params, postData)
  .then(function(res) { /* success handler */ })
  .catch(function(res) {
    var error = res.data.error;
    if (error && error.position) {
      var start = error.position;
      var end = start + vm.text.substr(start).search(/(\W|$)/);
      vm.selection = {start: start, end: end};
    }
  });
+4
1

.

<div ng-controller="MyController as vm">
  <textarea ng-model="vm.text" data-error-position="errorPosition" rows="5"></textarea>
  <button ng-click="vm.save()">Save</button>
</div>

, $prom ,

$scope.errorPosition = 50;

DOM- errorPosition.

+5

Source: https://habr.com/ru/post/1618755/


All Articles