Nick Audenaerde Nick Audenaerde - 4 months ago 9
AngularJS Question

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?

Answer

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'

}