How to update bind ng-model input value by using Jquery in AngularJS ?

Today now in this post i will show you How to update bind ng-model input value by using Jquery in AngularJS ? Sometimes, we may need to set a value of input box by using js. But if we bind with the ng-model of angular then we can’t set the value directly also with “val()” of jquery.

As like as Bellow example:

$("#my-name").val('test');

But we can set this on this way then it will display in our text box layout, but we can’t get from on submit function. So, we need to also trigger input on that way AngularJS can get on the controller method.

we can see in the bellow full example on that way we can understand how to solve this issue:

Example:
<!DOCTYPE html>
<html>
<head>
    <title>AngularJS - update bind ng-model input value from Jquery Code</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
	<div ng-app="mainApp" ng-controller="myController" id="mainController">
		<form name="form" ng-submit="submitForm()">
		 <input type="text" ng-model="form.name" id="my-name" />
        	 <button type="button" class="change-value">Change Value</button>
        	 <button type="submit">Submit</button>
		</form>
    </div>
        <script type="text/javascript">
         var mainApp = angular.module("mainApp", []);
         mainApp.controller('myController', function($scope, $timeout) {
            $scope.submitForm = function() {
                console.log($scope.form.name);
            }
         });
    </script>
    <script type="text/javascript">
    	$('.change-value').click(function(){
    		var myInput = $("#my-name");
    		myInput.val('test');
    		myInput.trigger('input');
    	});
    </script>
</body>
</html>

Read Also: How to implement infinite ajax scroll pagination in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →