简体   繁体   中英

how to get the value of an input field in angularJS controller

when I try to get the value of an input field in my controller it's always undefined,it seem 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. Thanks in advanced!

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.

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

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>

To get the value of an field from AngularJS, you would need to have ID set on it like this:

In AngularJS, do this to get the value:

$scope.RandomValue = angular.element('#RandomValue').val();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM