user3565261
user3565261

Reputation: 354

angularjs nullable select if null then

I have in my html angularjs select with null posibility:

<span class="nullable"> 
    <select ng-model="ViewLevel" ng-change="selChanged()"
            ng-options="camptype.name for camptype in campTypes">
                <option value="">-- choose campaign type --</option>
    </select>
</span>

and in js controller method to check if user selected something from list or nullable option

     $scope.selChanged = function() {
            if ($scope.ViewLevel == null) {
                $scope.getTypeData();
                console.log("nullek");
            } else {
                $scope.getCampaignData();
                console.log("nie nullek");
            }
        }

But it doesn't work. Always if clause is true, even if in firebug I can see that ViewLevel is not null. Why?

EDIT: screen from firebug
ViewLevel is an object with property but if clause was true:

diagram

Upvotes: 1

Views: 489

Answers (1)

harishr
harishr

Reputation: 18065

rather than checking against null, using ! operator, it will check for both null/undefined

    $scope.selChanged = function() {
        if (!$scope.ViewLevel) {
            $scope.getTypeData();
            console.log("nullek");
        } else {
            $scope.getCampaignData();
            console.log("nie nullek");
        }
    }

EDIT

as per angularjs recommendation: your ngModel must have a dot, and that would solve the problem for you.

//somewhere in your controller
$scope.selected = {}

and then in your html

<select ng-model="selected.ViewLevel" ng-change="selChanged()"
        ng-options="camptype.name for camptype in campTypes">
            <option value="">-- choose campaign type --</option>
</select>

and then again fix if in your function. check for $scope.selected.ViewLevel

 $scope.selChanged = function() {
    if (!$scope.selected.ViewLevel) {
        $scope.getTypeData();
        console.log("nullek");
    } else {
        $scope.getCampaignData();
        console.log("nie nullek");
    }
   }

Upvotes: 1

Related Questions