Javascript AngularJS - 将 this.value 传递给函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26463491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:55:42  来源:igfitidea点击:

AngularJS - passing this.value into a function

javascriptangularjsfunctionangularjs-scope

提问by boi_echos

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

我在本机 javascript 中有此代码,它可以正常工作。它记录文本框的当前值

<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:

然后我想在不使用模型的情况下在 AngularJS 上做同样的事情。这是代码:

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

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

But it always logs undefined!
Why?

但它总是记录undefined
为什么

回答by Miraage

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

据我所知,this在上下文中ng-*是一个scope.
您可以通过 访问boom($event.target.value)

回答by dfsq

The Angular way is to use ngModel:

Angular 的方法是使用ngModel

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

and in controller:

并在控制器中:

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

this.inputwill also work since thispoints to current scope object.

this.input由于this指向当前范围对象,因此也将起作用。

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

回答by Pedro Justo

'value' is not defined in scope.

“值”未在范围内定义。

I'll expand a little Miraage answer..

我会扩展一点 Miraage 答案..

thiswill 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)

this将参考范围。如果要访问 DOM 元素,请使用 $event。在回调函数中,您可以使用获取 DOM 元素值boom($event.target.value)