How to use Controller action to set value of form field in AngularJS
angularjs, angularjs-scope
Solution
You are overwriting the entire person object reference every time you invoke your set method. Notice how you create a new object every time. What you, most likely, intended is:
$scope.setFirstName = function(){
$scope.person.first_name = 'King';
}
Problem
How can I manually set the value of a form field via a controller's action? In my case I have a form with about 10 fields. One form field is a date field, and it has a button for setting its value to the current date, which I fetch via a service. I've tried manipulating the nested scope values but to no avail. The problem is after setting the value for the date field, the value for other form fields/scope values are destroyed. To illustrate the problem, see the below JSfiddle and code. JSFiddle to illustrate problem ``` <div ng:app> <form name="myForm" ng-controller="Ctrl">Age: <input type="text" data-ng-model="person.age" /> <br/>First Name: <input type="text" data-ng-model="person.first_name" /> <button ng-click="setFirstName()" type="button">Set First Name</button> <br/>Last Name: <input type="text" data-ng-model="person.last_name" /> <button ng-click="setLastName()" type="button">Set Last Name</button> <br/> </form> </div> function Ctrl($scope) { $scope.setFirstName = function () { $scope.person = { first_name: 'King' } }; $scope.setLastName = function () { $scope.person = { last_name: 'Kong' } }; } ```