Use attributes of the element in function in the scope of the controller

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 called just the function, and in the function that data would be 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 this does not work. I've already taken a look at the angular.element , but I found it much more difficult and not worth much , I would like something simpler, to leave the HTML clean without getting JS too dirty, separating the variables that I will use in two different attributes, in case I need to change them dynamically. How could I do that?

    
asked by anonymous 25.05.2018 / 03:22

1 answer

1

Pass in the method $event

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

Then just access the srcElement property of the $event expression:

$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><formng-submit="submit($event)" action="//example.com" method="POST">
  <input type="submit" id="submit" value="Submit" />
</form>

I also put it in the jsbin.com if the snippet does not work here.

Reference

25.05.2018 / 05:41