SITUATION:
This is just an example of what I'm trying to accomplish in a real project, where I get an array of names from a web service, then I locate the inputs with those names, select them and then set their values using jQuery.
PROBLEM:
What I need is to know how to update the ng-model
of those fields which I changed their value attribute using jQuery
I have tried these
- Update Angular model after setting input value with jQuery
- Angular model doesn't update when changing input programmatically
- Update HTML input value changes in angular ng-model
...but I haven't had luck with any of those options.
I'm using AngularJS v1.4.8 and jQuery v1.11.1
I have tried setting the input type to hidden
and type text
with style: display:none
but I can't get it working properly.
Here is a demo of what I'm trying to do. This has and input and an span bind with the same ng-model
.
When you click the button, it's supposed to change the input value using jQuery and then update the ng-model
.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
</head>
<body data-ng-app="app">
<div data-ng-controller="myCtrl as ctrl">
<span>Value: {{ctrl.myValue}}</span>
<input name="myId" type="hidden" data-ng-model="ctrl.myValue" />
<button data-ng-click="ctrl.changeValue('ValueChanged')">Change Value</button>
</div>
<script>
//my controller
angular.module('app', [])
.controller('myCtrl', function(){
var vm = this;
vm.wizard = {
changeValue: fnChangeValue
}
return vm.wizard;
function fnChangeValue(newValue){
var e = $('#myId');
e.val(newValue);
e.trigger('input'); //first option
//e.triggerHandler('change'); //second option
}
});
</script>
</body>
</html>