3

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'
        }
    };
}
user1322092
  • 4,020
  • 7
  • 35
  • 52

1 Answers1

5

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';
}
Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205
  • 2
    This works but is this 'correct' within JS with its Prototypal Inheritance? See this post regarding directly updating the higher level scope attributes: http://jimhoskins.com/2012/12/14/nested-scopes-in-angularjs.html Let me know your thoughts. – user1322092 Feb 02 '14 at 23:05
  • just wondering if you had a response to the link I shared earlier? – user1322092 Feb 12 '14 at 23:56
  • @user1322092 In this case the scope is exposing a person object, I do not see any risk here. The problem would arise if you had the `firstName` directly in the scope, as far as I can tell from the article you shared. – Edwin Dalorzo Jan 21 '15 at 23:40
  • @EdwinDalorzo : can you please take a look here, i want to set object to model , its saved to server as json, and when opened later it reads json and maps to model. The model have the object but the radio button does not select based on the object property. https://stackoverflow.com/questions/52168091/angularjs-ng-model-not-binding-to-ng-checked-for-input-type-radio-using-wit – NeverGiveUp161 Sep 10 '18 at 09:55