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. Commented 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).

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

1 Comment

Perfect! Nice one buddy!
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 Comments

Why not ng-click="boom(input)"? No need to pass in the event.
yeah, you can just use ng-click="boom(input)" just @yoshi said. And also I need not to use model for some reason
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)

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.