0

I use angular 1.3.x.

I have one big form. In a first step, I can edit the person name in the form so I have an object person bind to the scope and an input with ng-model:

$scope.person = { name: 'John' };

Later, in the same form, I have a list of contacts (which is person like above) and in this list I can have again the SAME person as previous.

I want that the person can be edited in the first part or last part of the form: if I change the name in the first input, it must be changed in the second input and vice versa.

I tries to do something like that:

$scope.contacts = [];
$scope.contacts.push(person);

The second form is correctly filled but if I change the name in the first input field, the second input field isn't updated.

Any idea how to do that? Thanks in advance.

4
  • Is this the only way you are loading data into $scope.contacts? If so this should work since you are sharing the same object reference. Commented Mar 20, 2015 at 14:10
  • $scope.contacts is at first loaded with an http request with restangular and I add the person after the user click on a button. Commented Mar 20, 2015 at 14:12
  • Checkout this fiddle: jsfiddle.net/HB7LU/11985 Hope it helps! Commented Mar 20, 2015 at 14:12
  • Isn't the fiddle working as you expect? Commented Mar 20, 2015 at 14:13

1 Answer 1

1

The objects are not properly updating because they are distinct objects with separate references. One work-around I found is to make sure to bind to the exact same object after filling the array's data.

After you populate the $scope.contacts, you should set your $scope.person to the proper object contained in that array. I use this approach to loop through the array and set the matching objects equal to each other. Then the bindings update properly.

.success(function (contacts) {
    $scope.contacts = contacts;

    //loop through and find first match, set them equal
    var foundMatch = $scope.contacts.some(function(contact) {
        if (areSame(contact, $scope.person)) { //you define areSame() logic
            $scope.person = contact;
            return true;
        }
        return false;
    });

Since your person can be set after a button press, you will have to use the loop-searching logic after the button press as well.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes when you asked from where contacts come, I understand my mistake. Thanks for your help.

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.