1

How do I pass the html element through my function when using AngularJS. This would work if you don't use AngularJS, but I think AngularJS confuses the "this" keyword with some other parent. How would I get this code to work?

angular.module('myApp', []).controller('myCtrl', function($scope) {
  $scope.MyFunction = function(element) {
    alert(element.value);
    element.focus();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <input ng-click="MyFunction(this)" value="Hello">
</div>
Frank
  • 2,109
  • 7
  • 25
  • 48

3 Answers3

2

I think you are looking for this.

<input ng-click="MyFunction($event)" value="Hello">

  // while in your controller

angular.module('myApp', []).controller('myCtrl', function($scope) {
  $scope.MyFunction = function($event) {

  //reference to the DOM element triggered the function
   var element =   $event.target;   
    element.focus();
  }
});

BUT ITS NOT GOOD PRACTICE TO DO IT THIS WAY IN ANGULAR JS

Umer Farooqui
  • 208
  • 2
  • 7
  • Would you mind explaining why this isn't good practice please? Because this solves my problem perfectly – Frank Apr 11 '18 at 06:36
  • look here, it explains well. [link](https://stackoverflow.com/questions/31032855/why-is-it-considered-a-bad-idea-to-manipulate-dom-in-controllers) and if you want to use them directives are the best: [here](https://stackoverflow.com/questions/37480150/manipulating-dom-in-angularjs-best-practice) – Umer Farooqui Apr 11 '18 at 08:06
1

you can use ng-model for assigning values to element and that's 2 way binding :)

    angular.module('myApp', []).controller('myCtrl', function($scope) {
      $scope.theValue = "Hello";
      $scope.MyFunction = function(value) {
        alert('Passed Value : ' + value  + ' Model Value : ' + $scope.theValue);
      }
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <input ng-model="theValue" ng-blur="MyFunction(theValue)">
</div>
manish
  • 1,450
  • 8
  • 13
  • Yes I know about ng-model but you can't do something like element.focus() with ng-model. So ng-model doesn't solve my problem here – Frank Apr 11 '18 at 06:29
0

In angular you can't work this way, try with event.target. You should try following way:

    <input ng-click="MyFunction()" value="Hello">

    angular.module('myApp', []).controller('myCtrl', function($scope) {
      $scope.MyFunction = function() {
        alert($(event.target).attr('value'));
        $(event.target).focus();
      }
    });
Hanif
  • 3,739
  • 1
  • 12
  • 18