wasim beg
wasim beg

Reputation: 73

ng-model is not working with ng-value in AngularJS

Below is my View page

<form name="form">
     <label>Name</label>
     <input name="name" type="text" ng-model='user.name' ng-value='emp.name' required />
     <span ng-show="form.name.$touched && form.name.$invalid">Name is required</span>
     <button ng-disabled="form.name.$touched && form.name.$invalid" ng-click='formUpdate()'>Update</button>
</form>

This is my controller

$scope.formUpdate = function() {
  $scope.status = false;
  $http({
  method : 'POST',
  url : 'model/update.php',
  data :   $scope.user ,
  headers : {'Content-Type': 'application/x-www-form-urlencoded'}          

  }).then(function mySuccess(response) {
    $scope.update = response.data;
    console.log(response.data); 
   }, function myError(response) {
    $scope.update = response.statusText;

   }); 
};

When I am using data: $scope.user in my HTTP call I am getting blank values on console but if I used data: $scope.emp, then I never get updated values of input fields rather getting old values of input fields.

Upvotes: 0

Views: 1186

Answers (2)

Mistalis
Mistalis

Reputation: 18269

ng-value binds the given expression to the value of the element.

As I understand your question, you are trying to initialize the input value to emp.name.

You should change your input to:

<input type="text" ng-model='user.name' ng-init='user.name = emp.name' required />

ng-init docs

Upvotes: 2

muratoner
muratoner

Reputation: 2672

try this code;

$scope.formUpdate = function(){
  $scope.status = false;
  $scope.$applyAsync();

  $http({
  method : 'POST',
  url : 'model/update.php',
  data :   $scope.user ,
  headers : {'Content-Type': 'application/x-www-form-urlencoded'}          

  }).then(function mySuccess(response) {
    $scope.update = response.data;
    $scope.$applyAsync();
    console.log(response.data); 
   }, function myError(response) {
    $scope.update = response.statusText;  
    $scope.$applyAsync();
   }); 

  };

Upvotes: 0

Related Questions