AngularJs - Select Options Watch Change

Fires event when selection changes. ng-options, $scope.$watch

by santhosh lanka

HTML

<div ng-app="" ng-controller="MyController">
    <select
        size="4"
        ng-model="category"
        ng-options="c.name for c in categories" 
    ></select>
    <div ng-show="!!category.id">
        Selected item: {{ category }}
    </div>
</div>

JavaScript

function MyController($scope) {
    $scope.category = {};
    $scope.categories = [
        {"id": 1, "name": "Hello"},
        {"id": 2, "name": "World"}
    ];
    $scope.$watch("category", function() {
        if (!!$scope.category.id) {
            alert($scope.category);
        }
    });
}