Javascript 将输入值绑定到 ng-click 按钮(将值作为参数发送)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31233876/
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-23 06:25:33  来源:igfitidea点击:

Bind input value to ng-click button (send value as parameter)

javascripthtmlangularjsangularjs-ng-clickangularjs-ng-model

提问by btmach

I'm trying to bind the value from an input field to the parameter of my method on ng-click. Here's what I got, but it doesn't work, and I am not too sure if it's possible to do it this way?:

我正在尝试将输入字段中的值绑定到我在 ng-click 上的方法的参数。这是我得到的,但它不起作用,我不太确定是否可以这样做?:

<input type="text" name="name" value="{{post.PostId}}" />
<button ng-click="getById(post.PostId)"></button>
<h1>{{post.Title}}</h1>


$scope.getById = function (id) {
        console.log(id);
        return $http.get('/api/Post/' + id);
    }

回答by JDTLH9

You should use ng-modeldirective for your input element.

您应该ng-model为输入元素使用指令。

Markup

标记

 <input type="text" name="name" ng-model="post.PostId" />
 <button ng-click="getById(post.PostId)"></button>
 <h1>{{post.Title}}</h1>

This will take care of 2-way model binding to your property post.PostId. Your ng-clickdirective will pick up the correct value entered in input element.

这将处理到您的 property 的 2-way 模型绑定post.PostId。您的ng-click指令将选取在 input 元素中输入的正确值。

See my working Plunk:)

查看我的工作Plunk:)