Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Controller action to set value of form field in AngularJS

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'
        }
    };
}
like image 368
user1322092 Avatar asked Nov 26 '25 13:11

user1322092


1 Answers

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';
}
like image 129
Edwin Dalorzo Avatar answered Nov 28 '25 14:11

Edwin Dalorzo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!