Kevin fu
Kevin fu

Reputation: 222

AngularJS : Function only updates variable in view after an event happens

I have a simple input field :

<input id = 'input' ng-model="addMe">

that is connected to a script :

<script>
    document.getElementById('input').onkeydown = function(event) {
        if (event.keyCode == 13) {
                angular.element(document.getElementById('input')).scope().addItem();
        }
   }
</script>

that is there so that whenever the user presses enter in the input field; the addItem function in AngularJS that adds the string from the input field into an array is called.

    $scope.addItem = function () {
        found = false;
        if (!$scope.addMe) return $scope.errorText = "Please Specify an Item";
        else {
            angular.forEach($scope.Products, function(value, key) {
                if (value.name.toUpperCase() == $scope.addMe.toUpperCase()){
                    $scope.cart_items.push({name : value.name, price : value.price});
                    $scope.grandTotal += value.price;
                    $scope.addMe = '';
                    $scope.errorText = '';
                    found = true;
                }
            });
            if(!found){$scope.errorText = "Item does not exist";}
        }
    }

note that cart_items, and products are arrays (not directly related to the problem)

The Function addItem is called when i press enter, passing the correct variables; but the variables like errorText, grandTotal, and also the data that is supposed to be pushed into the array cart_items, only updates when i press another key, or click.

i know the function is doing what it's supposed to do; because i used console.log to debug.

Upvotes: 0

Views: 59

Answers (1)

Stephane Janicaud
Stephane Janicaud

Reputation: 3627

Here is a sample code, change text field value, press Enter and look at the console output.

angular.module('app', []);

angular.module('app')
.controller('ExampleController', ['$scope', function($scope) {

	$scope.fieldValue = "Hello";

	$scope.keydown = function(event) {
		if(event.key === 'Enter') {
			$scope.addItem((event.srcElement || event.target).value);
		}
	}

	 $scope.addItem = function (value) {
        // do something
        console.log('Add item with value', value);
    }

}]);
<!doctype html>

<html lang="en" ng-app="app">
<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<body ng-controller="ExampleController">

<input type="text" ng-model="fieldValue" ng-keydown="keydown($event)">

</body>
</html>

Here is also a plunker with the code above

Upvotes: 1

Related Questions