Reputation: 2431
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>
Upvotes: 1
Views: 295
Reputation: 207
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
Upvotes: 2
Reputation: 3797
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();
}
});
Upvotes: 0
Reputation: 1458
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>
Upvotes: 1