javascript - AngularJS : Function only updates variable in view after an event happens -
i have simple input field :
<input id = 'input' ng-model="addme">
that connected script :
<script> document.getelementbyid('input').onkeydown = function(event) { if (event.keycode == 13) { angular.element(document.getelementbyid('input')).scope().additem(); } } </script>
that there whenever user presses enter in input field; additem
function in angularjs adds string input field array called.
$scope.additem = function () { found = false; if (!$scope.addme) return $scope.errortext = "please specify 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 not exist";} } }
note cart_items
, , products
arrays (not directly related problem)
the function additem
called when press enter, passing correct variables; variables errortext
, grandtotal
, , data supposed pushed array cart_items
, updates when press key, or click.
i know function doing it's supposed do; because used console.log
debug.
here sample code, change text field value, press enter , @ 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) { // console.log('add item 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 plunker code above
Comments
Post a Comment