从控制器角度js

时间:2018-04-26 06:07:12

标签: angularjs

我正在尝试将ng-model输入的值输入到我的控制器中。输入值具有值而不为空。 为什么这段代码不起作用?当您发出警报或控制台日志时,它会显示未定义。我错过了什么?真的很感谢你的帮助。这是我的代码

输入 - >值为1

    <input type="text" name="idval" ng-model="Data.idval"> 

JS

app.controller('Controller', function($scope, $http){

$scope.fetchvalue = function(){

  var id = $scope.Data.idval; // not working
  var id = $scope.idval; // even this one

  alert(id); // its undefined

    $http.post(
        "query.php", {
            'ID': id,
        }
    ).then(function(response) {

       console.log(response.data);

    });
}});

3 个答案:

答案 0 :(得分:1)

以下是您的代码的可行解决方案:

您需要声明object并将其绑定到ng-model

<强> $scope.Data = {};

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
   $scope.Data = {};
 $scope.fetchvalue = function(){
    var id = $scope.Data.idval; // not working
    alert(id); // its undefined
 }   
});
&#13;
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="formCtrl">
  <form novalidate>
    <input type="text" name="idval" ng-model="Data.idval"> 
    <button ng-click="fetchvalue()">Submit</button>
  </form>
  </div>



</body>
</html>
&#13;
&#13;
&#13;

Here is a working Plunker

答案 1 :(得分:0)

我理解,

看到您定义了__new__两次,首先从id获取值,该值必须将ng-model值分配给ng-model变量,并覆盖id undefined 变量名为id

您可以删除第idval行或

var id = $scope.idval;修改为alert(id);

答案 2 :(得分:0)

在使用它之前,您需要在某处声明它。

$scope.DATA = ""
var id = $scope.Data.idval;

试试这个

相关问题