Reputation: 75
When I try to get the value of an input field in my controller it is always undefined. It seems like the angularJS two-binding is not working.
This is the angularJS code:
app.controller('MainCtrl', $scope)
{
var quan = $scope.quantity;
alert(quan);
}
the html
<form ng-controller="MainCtrl" class="form-inline" role="form" padding-left:10em">
<input type="text" class="form-control" id="quantity" ng-model="quantity" />
</form>
I cannot get the value of the input in my controller.
Upvotes: 1
Views: 4459
Reputation: 467
To get the value of an field from AngularJS, you would need to have ID set on it like this:
<input id="RandomValue" type="text">
In AngularJS, do this to get the value:
$scope.RandomValue = angular.element('#RandomValue').val();
Upvotes: -1
Reputation: 75
I found an approach that work for me.
this is the angular
$scope.changedValue = function (item,quan)
{
if (item != null && quan !=null)
{
$http.get('/api/product/'+ item).success(function (data)
{
$scope.amount = parseFloat(data.price * quan);
});
}
}
and the is the html
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<form class="form-inline" >
<input type="text" class="form-control" id="quantity" ng-model="quantity" />
<select class="form-control" id="selected_id" ng-model="selected_id" ng-options="c.Value as c.Text for c in pcategoryA"
ng-change="changedValue(selected_id,quantity)">
</form>
</div>
Upvotes: 0
Reputation: 575
If you add this into your controller, it will show alert every time you change the input value.
$scope.$watch(function() {
return $scope.quantity;
}, function(quantity) {
alert(quantity);
});
Upvotes: 0
Reputation: 1105
First, your syntax is incorrect, see hadiJZ answer. Second, the controller will be called once after it is created, so if you change the text afterwards, you will not see the alert another time.
Upvotes: 1