user675712 user675712 - 1 year ago 84
AngularJS Question

Programmatically set the value of an input field in angularjs

I have a requirement to pre-populate an input field with the value of another input field. So, once the first field loses focus, the second field gets the same value. The field is editable, but initially, it has the value of the first field. I've found that the ngModel of the second field is not updated.

I do this to set the value of the second field:

$("#" + fieldId).val(newstring);

Here's the HTML for the first field:

<td class="formLabel" vAlign="top" align="left">
<input validate-date-time val-type="date" val-start="true" val-end-id="endDate" id="startdate" size="10" max="10" width="20" ng-model="newEvent.startDate">

Here's the HTML for the second field:

<td class="formLabel" vAlign="top" align="left">
<input size="10" validate-date-time val-type="date" id="endDate" max="10" width="20" ng-model="newEvent.endDate">

This is done in a directive, by the way. Any pointers on how to make this work?
I've tried calling scope.$apply and scope.$digest after setting the input val to no avail. And if I shouldn't use jQuery, whats the angular way of setting the value?

Answer Source

Try something like this:

// in the controller, add
$scope.isStartDateInitialized = false;
$scope.onStartDateSet = function() {
    if (!$scope.isStartDateInitialized) {
        $scope.isStartDateInitialized = true;
        $scope.newEvent.endDate = $scope.newEvent.startDate;

<!-- add the following attribute to the start date input -->
<input ... ng-blur="onStartDateSet()" />

NOTE 1: The above code assumes that you only want to programmatically update the end date the very first time the start date is set. If you want it to always be set to the start date when the start date changes, then you can use ng-change instead of ng-blur.

NOTE 2: You should remove the following JQuery code that you mentioned:

$("#" + fieldId).val(newstring);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download