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'
        }
    };
}

1 Answer 1

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';
}
Sign up to request clarification or add additional context in comments.

4 Comments

This works but is this 'correct' within JS with its Prototypal Inheritance? See this post regarding directly updating the higher level scope attributes: jimhoskins.com/2012/12/14/nested-scopes-in-angularjs.html Let me know your thoughts.
just wondering if you had a response to the link I shared earlier?
@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.
@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. stackoverflow.com/questions/52168091/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.