在AngularJS中存储文本输入的值

时间:2022-08-22 08:53:32

I have an input:

我有一个输入:

In the controller I want to obtain the value of the text input by setting available. For example: vm.inputValue = document.getElementById('link').value;

在控制器中,我想通过设置可用来获取文本输入的值。例如:vm.inputValue = document.getElementById('link')。value;

It breaks my code as I get a console error of: TypeError: Cannot read property 'value' of null

当我收到控制台错误时,它会破坏我的代码:TypeError:无法读取null的属性“value”

What am I doing wrong?

我究竟做错了什么?

2 个解决方案

#1


0  

AngularJS have a directive that does it to you, the ng-model. It binds in a variable the input you enter in the HTML and it reflect the changes you make in the variable inside your controller in JavaScript.

AngularJS有一个指令,它可以为你做ng-model。它在变量中绑定您在HTML中输入的输入,它反映您在JavaScript中的控制器内的变量中所做的更改。

In your HTML

在你的HTML中

<input type="text" ng-model="vm.myText">
{{ vm.myText }} <!-- This is output the value of vm.myText in the HTML -->
<button ng-click="vm.logData()"></button>

In your JavaScript

在你的JavaScript中

function MyController(){
  var vm = this;

  vm.myText = '';

  vm.logData = logData;

  function logData(){
    console.log('Your data is ', vm.myText); 
    // This easy, you can access your value in the JavaScript
  }
}

#2


0  

Probably you forget to set the id (id = "link")of the input field in HTML:

可能你忘记在HTML中设置输入字段的id(id =“link”):

<input id = "link" type = "text">

Also, you can do the same thing using ng-model

此外,您可以使用ng-model执行相同的操作

<input ng-model = "vm.inputValue" type = "text">

And from controller, you can get the correct value if you define a scope variable:

从控制器中,如果定义范围变量,则可以获得正确的值:

$scope.vm = {};
$scope.vm.inputValue = "";

#1


0  

AngularJS have a directive that does it to you, the ng-model. It binds in a variable the input you enter in the HTML and it reflect the changes you make in the variable inside your controller in JavaScript.

AngularJS有一个指令,它可以为你做ng-model。它在变量中绑定您在HTML中输入的输入,它反映您在JavaScript中的控制器内的变量中所做的更改。

In your HTML

在你的HTML中

<input type="text" ng-model="vm.myText">
{{ vm.myText }} <!-- This is output the value of vm.myText in the HTML -->
<button ng-click="vm.logData()"></button>

In your JavaScript

在你的JavaScript中

function MyController(){
  var vm = this;

  vm.myText = '';

  vm.logData = logData;

  function logData(){
    console.log('Your data is ', vm.myText); 
    // This easy, you can access your value in the JavaScript
  }
}

#2


0  

Probably you forget to set the id (id = "link")of the input field in HTML:

可能你忘记在HTML中设置输入字段的id(id =“link”):

<input id = "link" type = "text">

Also, you can do the same thing using ng-model

此外,您可以使用ng-model执行相同的操作

<input ng-model = "vm.inputValue" type = "text">

And from controller, you can get the correct value if you define a scope variable:

从控制器中,如果定义范围变量,则可以获得正确的值:

$scope.vm = {};
$scope.vm.inputValue = "";