Use element attributes in function of controller scope

Asked

Viewed 39 times

0

I have a form that calls a function when being submitted through the attribute, for example:

ng-submit="submit('POST', 'example.com')"

I would like this attribute to be just called the function, and in the function this data is taken through the other attributes, for example:

<form action="example.com" method="POST" ng-submit="submit()">
    <! ... >
</form>

$scope.submit = function() {
    let action = this.action;
    let method = this.method;
    // ...
}

But using only the this doesn’t work. I’ve already looked at the angular element., but I found it much more work and not worth much, I would like something simpler, that leaves the HTML clean without mucking up the JS, separating the variables that I will use in two different attributes, in case I need to change them dynamically. How could I do that?

1 answer

1


Pass the expression as a parameter in the method $event

<form ng-submit="submit($event)" action="http://example.com" method="POST">

then just access the property srcElement of expression $event:

$scope.submit = function(e) {
  e.preventDefault(); // Previne o envio do form
  console.log(e.srcElement.action);
  console.log(e.srcElement.method);
}

See working

angular.module('PTstackoverflow', [])
  .controller('301786', ['$scope', function($scope) {
    $scope.submit = function(e) {
      e.preventDefault();
      console.clear();
      console.log(e.srcElement.action);
      console.log(e.srcElement.method);
    };
  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.0/angular.min.js"></script>

<form ng-submit="submit($event)" action="//example.com" method="POST">
  <input type="submit" id="submit" value="Submit" />
</form>

I also put in the jsbin.com if the snippet doesn’t work here.

Reference

Browser other questions tagged

You are not signed in. Login or sign up in order to post.