10

I have this code in native javascript and it works all right. it logs the textbox's current value

<script>
    var boom = function(val) {
        console.log(val);
    };
</script>

<input type="text" onclick="boom(this.value)"/>

Then I want to do the same on AngularJS without using model. Here is the code:

$scope.boom = function(val) {
    console.log(val);
};

<input type="text" ng-click="boom(this.value)"/>

But it always logs undefined!
Why?

1
  • You should read some documentation about angularJS's controllers, scope, and directives. Follow some tutorials before start typing code. Oct 20, 2014 at 11:41

3 Answers 3

23

As I know, this in context of ng-* is a scope.
You may access via boom($event.target.value).

1
  • Perfect! Nice one buddy! Oct 20, 2014 at 10:39
10

The Angular way is to use ngModel:

<input type="text" ng-model="input" ng-click="boom()"/>

and in controller:

var boom = function() {
    console.log($scope.input);
};

this.input will also work since this points to current scope object.

If you still want to avoid model then you can use event object:

<input type="text" ng-click="boom($event)"/>

and

var boom = function($event) {
    console.log($event.target.value);
};
2
  • 2
    Why not ng-click="boom(input)"? No need to pass in the event.
    – Yoshi
    Oct 20, 2014 at 10:47
  • yeah, you can just use ng-click="boom(input)" just @yoshi said. And also I need not to use model for some reason Oct 21, 2014 at 1:33
1

'value' is not defined in scope.

I'll expand a little Miraage answer..

this will refer to the scope. If you want to access the DOM element use $event. In the callback function you can get the DOM element value using boom($event.target.value)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.