简短的if语句总是返回true

时间:2014-01-31 05:49:20

标签: javascript angularjs

我有一个列出组的下拉菜单。每个组都包含一个属性(布尔值),用于确定组所有者是用户还是其他组

如果组所有者是用户,我会获取组ownerID并将其与一组用户进行比较,以确定哪个用户与该ID匹配,并将该用户设置为selectedOwner。但是,如果群组所有者是一个群组,我会尝试遍历我的所有群组以查找匹配并将该群组设为selectedOwner

这是我的控制器功能:

$scope.groupOwner = function (){
    var temp = $scope.selectedGroup.ownerIsUser ? $scope.users : $scope.groups;
    var index = temp.length; 
    console.dir(temp);
    while(index--){
        if($scope.selectedGroup.owner === temp[index].id){
            $scope.selectedOwner = temp[index];
            console.log($scope.selectedOwner);
            break;
        };
    };      
};

每当下拉列表发生变化时,它都会调用groupOwner来检查selectedUser.ownerIsUser属性,以确定我应该查看哪个数组,usersgroups

但是,无论selectedGroup所有者属性设置为什么,temp变量始终返回true。

这就是对象的样子:

User = { 
name: Demo Administrator,
id: 90,
domain: i:0#.w|itun\demoadmin_compulite,
email: ,
isAdmin: False
 }

selectedGroup =  { 
name: Test Group,
id: 10,
description: ,
owner: 88,
ownerIsUser: False
 }

HTML:

<div class="topRow">
    <label for="entityDropDown">Select a Group:</label>
    <select id="entityDropDown" ng-model="selectedGroup" ng-options="group as group.name for group in groups" ng-change="getGroupInfo(selectedGroup)"></select>
    <div class="delGroupBtn"><a>&#10006;</a>

    </div>
</div>

对象的控制台输出:

Object {name: "Test Group 4", id: "117", description: "", owner: "71", ownerIsUser: "False"…}
description: ""
id: "117"
name: "Test Group 4"
owner: "71"
ownerIsUser: "False"
__proto__: Object

解决:

$scope.groupOwner = function (){
    //object stores string not booleans
    var isUser = $scope.selectedGroup.ownerIsUser === "True"? true : false;  
    var owner = isUser ? $scope.user : $scope.group;
    var index = owner.length; 
    console.dir(owner);
    while(index--){
        if($scope.selectedGroup.owner === owner[index].id){
            $scope.selectedOwner = owner[index];
            console.log($scope.selectedOwner);
            break;
        };
    };      
};

2 个答案:

答案 0 :(得分:1)

你的变量是“False”而不是boolean false。“False”是一个字符串,总是计算为true。

var temp = $scope.selectedGroup.ownerIsUser ? $scope.users : $scope.groups;

将始终设置temp = $scope.users

一些javascript控制台测试示例:

> a = "False"
> "False"
> b = false
> false
> testValue = a ? 1 : 2;
> 1
> testValue = b ? 1 : 2;
2

答案 1 :(得分:0)

此对象目前未定义

selectedGroup:  { 
name: Test Group,
id: 10,
description: ,
owner: 88,
ownerIsUser: False
}

应使用所有变量值

进行定义
selectedGroup:  { 
name: Test_Group, // or 'Test Group'
id: 10,
description: '',
owner: 88,
ownerIsUser: false
}