Chris
Chris

Reputation: 639

AngularJs: Copy the data using ng-value but model does not update

I'm having an issue on updating or assigning the value or data into the model using ng-value.

I would like to copy any values in the DisplayName model to CopyDisplayName and using below directives i was able to do that, But the problem is the model CopyDisplayName doesn't have any value when I submit my changes. It can only have if I inputted it manually.

<input type="Text" ng-model="DisplayName" ng-disabled="true" />
<input type="Text" ng-model="CopyDisplayName" ng-value="DisplayName" />

Forgot to include that the DisplayName is disabled.. the data will came from service call.

Upvotes: 2

Views: 3917

Answers (5)

Diwas Subedi
Diwas Subedi

Reputation: 3

what you can do in controller is watch the model and copy that value whenever it is changed($watch will do that for you) you dont need ngChange on the HTML.

$scope.$watch('displayName', function() {
      $scope.copyDisplayName = $scope.displayName; 
});

Upvotes: 0

whoknows
whoknows

Reputation: 306

ngValue

Binds the given expression to the value of or input[radio], so that when the element is selected, the ngModel of that element is set to the bound value.

You can take a look in this documentation.

So basically, the one you're doing right now will not work.

You can do this in your angular controller:

$scope.copyValue = function () {
    $scope.copyDisplayName = $scope.displayName; 
}

In html:

<input type="text" ng-model="displayName" ng-change="copyValue()" />

Upvotes: 2

Vasyl
Vasyl

Reputation: 1423

To have copy updated you need copy value by reference. For that you need to wrap displayName to object: $scope.model = {DisplayName: 'val'}; and make a copy of it: $scope.modelCopy = $scope.model;

 <input type="Text" ng-model="model.DisplayName" ng-disabled="true" />
 <input type="Text" ng-model="modelCopy.DisplayName" ng-value="DisplayName" />

JSFiddle

Upvotes: 0

Shekhar Khairnar
Shekhar Khairnar

Reputation: 2691

You can add $watch on DisplayName as:

$scope.$watch('DisplayName',function(newValue, oldValue){
   console.log(newValue +":"+oldValue)
   $scope.CopyDisplayName = newValue;
});

Upvotes: 0

New Dev
New Dev

Reputation: 49620

Just assign one variable to another:

// in the controller
$scope.CopyDisplayName = $scope.DisplayName;

If you need to keep them in sync (and for some reason, you don't want to just use the same variable), then you can keep them updated via ng-change:

<input type="Text" ng-model="DisplayName" ng-change="CopyDisplayName = DisplayName" />

Directives like ng-value (or ng-checked) only toggle the attributes in the DOM - they do not alter the View Model.

Upvotes: 1

Related Questions