Mehandi Hassan Mehandi Hassan - 4 months ago 69
AngularJS Question

How do i get textbox value in angularjs?

I am trying to create simple web page using angular.
I have 2 textbox and also 2 buttons.
1 button to set value prdefine in textbox
2 write some text and add.
When i will click on add button then textbox 1and 2 should printon screen another place.

Here the code.
index.html

<!DOCTYPE html>
<html lang="en" ng-app="chatApp">
<head>
<meta charset="UTF-8">
<title>Chat Application</title>
<script src="scripts/angular.min.js"></script>
<script src="scripts/app.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<script>
function myFunction() {
document.getElementById("Text1").value = "Johnny Bravo";
}
</script>
<body ng-controller="chatController">
<div class="container">
<div class="chatArena">

<div class="userList">
<ul>
<li ng-repeat="person in listPeopleAdded" >{{person.name}}</li>
<li ng-repeat="person in pretext" >{{person.name}}</li>

</ul>
</div>
</div>
<div class="chatAdder">
<input type='text' ng-model='textbox' name='textbox1' id='Text1'>
<button onclick="myFunction()" ng-click="pset(textbox)">set value</button>
<br>
<br>

<input type="text" name="personName" class="chatInputPersonName" ng-model="personName">
<button ng-click="addPerson()">Add Value</button>
</div>
</div>
</body>
</html>


app.js

var app = angular.module('chatApp',[]);

app.controller('chatController',function($scope){

$scope.pretext=[];
$scope.listPeopleAdded = [];
$scope.addPerson = function(){
$scope.listPeopleAdded.push({name:$scope.personName})

}
$scope.pset = function(textbox){
alert($scope.textbox)
$scope.pretext.push({name:$scope.textbox})
}

});


in app.js alert($scope.textbox) show undefined value.

Answer

Try this , its working You can use angular.element(document.getElementById("Text1")) to get value from javascript. And this value set to scope variable.

No need to send any value to function since textbox is scope value.

  $scope.pset = function(){
    var   x=angular.element(document.getElementById("Text1"));      
    $scope.textbox = x.val();
    alert($scope.textbox);
  }

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
 
  $scope.pset = function(){
     var   x=angular.element(document.getElementById("Text1"));      
    $scope.textbox = x.val();
    alert($scope.textbox);
  }
});
<script data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js" data-require="angular.js@1.4.x"></script>
 <script>
   window.onload=function(){
  // document.getElementById("Text1").value = "Johnny Bravo";
  
   }
   function myFunction() {
document.getElementById("Text1").value = "Johnny Bravo";
}
   
 </script>  

<body ng-app="plunker" ng-controller="MainCtrl">
 <input type='text' ng-model='textbox' name='textbox1' id='Text1'>
 <button onclick="myFunction()" ng-click="pset()">set value</button>
  </body>