【问题标题】:Storing value of a text input in AngularJS在AngularJS中存储文本输入的值
【发布时间】:2018-02-23 00:44:42
【问题描述】:

我有一个输入:

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

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

我做错了什么?

【问题讨论】:

  • 请添加目标元素的html代码

标签: javascript angularjs input


【解决方案1】:

AngularJS 有一个指令 ng-model。它将您在 HTML 中输入的输入绑定到一个变量中,并反映您在 JavaScript 控制器中对变量所做的更改。

在您的 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>

在你的 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】:

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

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

    另外,你可以使用ng-model做同样的事情

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

    如果你定义一个范围变量,你可以从控制器中得到正确的值:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-20
      • 2016-08-22
      • 1970-01-01
      • 2019-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多