Search code examples
javascriptangularjsdata-bindingangular-ngmodelangularjs-ng-model

Updating different $scope object properties via ng-model


Please look at the code below. Why does the $scope.data variable not update, when inserting valid values in the input fields? How can I achieve this?

Codepen: http://codepen.io/uloco/pen/jboorN

HTML

<div ng-app="app" ng-controller="AppController" class="content">
    <input type="tel" ng-model="form.phone" placeholder="phone" />
    <input type="email" ng-model="form.email" placeholder="email" />
    <p>{{form}}</p>
    <p>{{data}}</p>
</div>

JS

angular
.module('app', [])
.controller('AppController', function($scope) {
    $scope.form = {};
    $scope.data = {
        foo: 'bar',
        phone: $scope.form.phone,
        email: $scope.form.email
    }
});

Solution

  • Why does the $scope.data variable not update?

    Because there is no connection between $scope.data and $scope.form. Those are two separate objects with independent properties, and you are changing properties of the $scope.form.

    If you really want to have two separate objects you will need to sync them manually either with $scope.$watch on the $scope.form

    $scope.$watch('form', function(obj) {
        $scope.data.phone = obj.phone;
        $scope.data.email = obj.email;
    }, true);
    

    Demo: http://codepen.io/anon/pen/PPvvBr?editors=101

    or with ngChange directives:

    <input type="tel" ng-model="form.phone" placeholder="phone" ng-change="sync()" />
    <input type="email" ng-model="form.email" placeholder="email" ng-change="sync()" />
    

    and

    $scope.sync = function() {
        $scope.data.phone = $scope.form.phone;
        $scope.data.email = $scope.form.email;
    };
    

    Demo: http://codepen.io/anon/pen/bVyyQN?editors=101

    ngChange solution is preferred in this case. However, if you have more then 2 fields then $watch could be simpler.