angularjs nullable如果为null则选择

时间:2014-08-05 14:12:59

标签: javascript html angularjs null

我在我的html angularjs中选择了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>

并在js控制器方法中检查用户是否从列表或可空选项

中选择了某些内容
     $scope.selChanged = function() {
            if ($scope.ViewLevel == null) {
                $scope.getTypeData();
                console.log("nullek");
            } else {
                $scope.getCampaignData();
                console.log("nie nullek");
            }
        }

但它不起作用。 Always if子句为true,即使在firebug中我可以看到ViewLevel不为null。为什么呢?

编辑:来自萤火虫的屏幕
ViewLevel是一个带属性的对象,但if子句为true:

diagram

1 个答案:

答案 0 :(得分:1)

而不是检查null,使用!运算符,它将检查null / undefined

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

修改

根据angularjs建议:您的ngModel必须有一个点,这样才能解决问题。

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

然后在你的HTML中

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

然后再次修复你的功能。检查$ scope.selected.ViewLevel

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