$scope.$watch example

by Kristopher Johnson

HTML

<body ng-app="demoApp">
    <div ng-controller="DemoController">
        <div>
            <select ng-model="selectedCustomer"
                ng-options="customer as customer.name for customer in customers">
            </select>

            <p>The selected customer is {{ selectedCustomer.name }}.</p>
        </div>

        <div>
            <p>The watched customer is {{ watchedCustomer.name }}.</p>
        </div>
    </div>
</body>

JavaScript

angular.module('demoApp', []).controller('DemoController', function($scope) {

    $scope.customers = [
        { name: 'First Customer', value: 1 },
        { name: 'Second Customer', value: 2 }
    ];
    $scope.selectedCustomer = $scope.customers[1];
    
    $scope.$watch('selectedCustomer', function(newValue) {
        $scope.watchedCustomer = newValue;
    });
});