Nick Audenaerde
Nick Audenaerde

Reputation: 1025

form value not showing when using ng-model angularjs

I got a form for editing products, the value is showing in the inspector, however not in the form. They do show when I remove ng-model from my code.

In this line the value shows in the inspect element, but not in the form:

<input type="text" class="form-control" placeholder="Product naam" 
value="{{product.title}}" ng-model="formData.title"/>

In this line the value shows in the inspect element, and in the form:

<input type="text" class="form-control" placeholder="Product naam" 
value="{{product.title}}"/>

However I need ng-model to pass the data.

Any suggestions?

Upvotes: 4

Views: 10954

Answers (2)

Akhilesh Kumar
Akhilesh Kumar

Reputation: 919

If data-ng-model="form.test" then how you will populate its value in input box. Just modifying answer of Renan so that it will help you out to understand the solution more easily.

    angular.module('app', []);

    angular.module('app')
      .controller('MainController', mainController)

     mainController.$inject = ['$scope'];

    function mainController($scope) {
      $scope.form = {};
      $scope.form.test = 'value of the input'

    }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">

  <div ng-controller="MainController">
    <input type="text" data-ng-model="form.test">
  </div>

</div>

Upvotes: 0

Renan Ferreira
Renan Ferreira

Reputation: 2150

You don't need the value property in your input tag. The ng-model will already do the binding for you. If you define formData.title in your controller, it will reflect on the value of your input.

The same way, if the user changes the value of the input, it will reflect on the value declared in your controller.

This is the famous Two-way Data Binding of AngularJS. One awesome and dangerous feature of the framework

Take a look at this Fiddle:

http://jsfiddle.net/relferreira/kLcqwuqf/

HTML:

<div ng-app="app">

  <div ng-controller="MainController">
    <input type="text" data-ng-model="test">
  </div>

</div>

JS:

angular.module('app', []);

angular.module('app')
    .controller('MainController', mainController)

mainController.$inject = ['$scope'];
function mainController($scope){

  $scope.test = 'value of the input'

}

Upvotes: 8

Related Questions