gandharv garg
gandharv garg

Reputation: 2171

Is it possible to prefill a form using ng-model in angularjs?

I have a simple form

 <form>
    Name:
    <input type="text" ng-model="edit"><br />
  </form>

and a simple array in the controller

$scope.statuses = [
    {value: 1, text: 'status1'},
    {value: 2, text: 'status2'},
    {value: 3, text: 'status3'},
    {value: 4, text: 'status4'}
  ]; 

I am repeating the array in the view

<div ng-repeat="x in statuses">{{x.text}}<button ng-model="edit">edit</button></div>

so i was wondering when i click the edit button can the data be populated inside the form input field using ng-model ? plunker

Upvotes: 0

Views: 2301

Answers (1)

Pierre-Alexandre Moller
Pierre-Alexandre Moller

Reputation: 2354

You can do that by using a ng-click in yout button instead of a ng-model.

Your button will have to run a function on click, just like this :

<button ng-click="editFunction(x)">edit</button>

And then in your controller, there is the function :

$scope.editFunction = function(x){
   $scope.edit = x.text;
}

In this function you will get the value of x and set this value in your form ng-model.

There is a working Plunker

Upvotes: 1

Related Questions