Mahfuz Shishir Mahfuz Shishir - 27 days ago 7
AngularJS Question

2-way data binding not work for me

In html file the value of input field updated. And using $scope, first time i am able to assign input field. But when i changed input field in htlm, input field value is changed but in js, console log value not changed. I want to get the updated value in js function.And I am using laravel framework.In practice it works. But my project it does not work. Thank you.

index.html

<div class="form-group">
<div class="col-sm-12">
<input type="text" class="form-control"
id="send_amount"
name="send_amount"
ng-model="send_amount"
ng-keyup="calculateReceivedAmount()" required>
</div>
@{{ send_amount }}




And my js file

var exchange = angular.module('app', []);
exchange.controller('MoneyExchangeController', MoneyExchangeController);
function MoneyExchangeController($scope, $http) {
$scope.send_amount = 100;
$scope.calculateReceivedAmount = function () {
console.log($scope.send_amount);
}
}

Answer Source

AngularJS has problems with binding non-object variables, try binding your input as follows :

index.html

<input type="text"
       class="form-control"
       id="send_amount"
       name="send_amount"
       ng-model="send_amount.value"
       ng-keyup="calculateReceivedAmount()"
       required />

app.js

var exchange = angular.module('app', []);
exchange.controller('MoneyExchangeController', MoneyExchangeController);
function MoneyExchangeController($scope, $http) {
    $scope.send_amount = {
        value: 100
    };
    $scope.calculateReceivedAmount = function () {
        console.log($scope.send_amount.value);
    };
}