Georgi Naumov
Georgi Naumov

Reputation: 4211

How to check if select is selected in AngularJS

How I can check if select is selected in AngularJS. I tried to use

$scope.$watch

On models for these selects but I think this is not efficient.

This is example of my current solution. html:

<div ng-app>
<div ng-controller="testCtrl">
    <select ng-model="first">
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
    <select ng-model="second">
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
</div>
</div>

And JavaScript code:

function testCtrl($scope) {
$scope.$watch('first + second', function () {
            if (angular.isDefined($scope.first) &&
                angular.isDefined($scope.second)
                ) {
               alert("user chose from the two drop downs.");
            }

        });
}

And here is jsfiddle:

http://jsfiddle.net/zono/atN5n/1/

But I think this solution is not effective.

Upvotes: 0

Views: 6099

Answers (2)

Brocco
Brocco

Reputation: 65013

Typically it is considered bad form to have watches set up on your controller (they work much better in directives).

In each of your selects you can add

<select ng-change="selectChanged()"...

Then in your controller you can handle this event, as you were intending to do with your watch

function testCtrl($scope) {
    $scope.selectChanged = function () {
        if (angular.isDefined($scope.first) &&
            angular.isDefined($scope.second)) {
            alert("user chose from the two drop downs.");
        }
    });
}

Working Fiddle

Here is some more information regarding this: http://www.benlesh.com/2013/10/title.html

Upvotes: 2

Blackhole
Blackhole

Reputation: 20401

Hint: AngularJS is providing ngFocus and ngBlur directives.

Upvotes: 1

Related Questions