0

I'm trying to get the value of my ng-model input to my controller. The input value has a value and not empty. Why this code is not working? It says undefined when you alert or console log. What did i missed? really appreciate your help. here is my code

input --> the value is 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);

    });
}});
5
  • is your input value hardcoded? Commented Apr 26, 2018 at 6:10
  • wen is that fetchvalue called, and have you taken Data object? Commented Apr 26, 2018 at 6:12
  • check your controller name Commented Apr 26, 2018 at 6:13
  • paste your complete controller Commented Apr 26, 2018 at 6:16
  • wen the button is click, called the fetchvalue @Sravan Commented Apr 26, 2018 at 6:19

3 Answers 3

2

Here is a working solution for your code:

You need to declare an object and bind it to ng-model,

$scope.Data = {};

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

Here is a working Plunker

Sign up to request clarification or add additional context in comments.

2 Comments

it works! i missed this code in my controller $scope.Data = {}; Thanks @Sravan
Glad to help you :).
0

I understand,

see you defined id twice, first id get the value from ng-model which must be assigning ng-model value to id variable and you override id with undefined variable called idval.

You can either remove line var id = $scope.idval; or

modify alert(id); as alert($scope.Data.idval)

2 Comments

i declare only id twice for showing that both of two are not working. but when in operation only one id at a time. Thanks @Kishor Pawar.
aha ok. That's why we expect more actual code here in post.
0

You need to declare it somewhere before you use it.

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

Try this out

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.