1

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.

4 Answers 4

1

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.

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

2 Comments

So how can I get the value in the controller?
That depends on where you get the value from. If the original data is in the scope, you could use a watch: $scope.$watch('value', function(changedValue, previousValue){ ... do something with changedValue }); The watch will fire whenever the value changes within the $scope. A more clean approach would be to utilize ng-change, though this only works if you only have one specific element (in your case the input field) that writes to the value, or all elements call the change function.
0

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

Comments

0

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>

Comments

-1

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();

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.