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>

3
  • This will not work. You need to write the directive to set focus on input. Commented Apr 11, 2018 at 5:23
  • 2
    Possible duplicate of How to set focus on input field? Commented Apr 11, 2018 at 5:23
  • You have all the html element in your link function within the element param already. Commented Apr 11, 2018 at 7:56

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Would you mind explaining why this isn't good practice please? Because this solves my problem perfectly
look here, it explains well. link and if you want to use them directives are the best: here
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>

1 Comment

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
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();
      }
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.