1

使用服务我成功检索 JSON 数组,然后我将该数据泵入我的控制器并尝试与数据绑定值进行比较,因为用户输入了他们想要的用户名,但我没有显示日志值应该匹配。这是我所拥有的:

角服务:

loginApp.factory('userData', function($http, $log) {
    return {
        getUsers: function(scb) {
            $http({method: 'GET', url: 'somelink/ajax/current_users.php'}).
                    success(function(data, status, headers, config) {
                $log.info(data, status, headers(), config);
                scb(data);
            }).
                    error(function(data, status, headers, config) {
                $log.warn(data, status, headers(), config);
            });

        }
    };
});

我的控制器:

loginApp.controller('loginController',
        function loginController($scope, userData) {

            // If I run a log on the `activeusers` 
            // I get the same console log as below    
            userData.getUsers(function(current_users) {
                $scope.activeusers = current_users;
            });

            $scope.createAccnt = {
                fname: "",
                lname: "",
                username: function(inValue) {
                    for (var i = 0; i < $scope.activeusers.length; i++) {
                        if ($scope.activeusers[i].username == inValue) {
                            console.log("Username matches existing!!");
                        }
                    }
                },
                email: ""
            };
}

返回的 JSON 数组:

[
    {
        "user_id": "1",
        "username": "userone",
        "password": "",
        "first_name": "",
        "last_name": "",
        "email": "",
        "active": "",
        "auth_token": ""
    },
    {
        "user_id": "2",
        "username": "usertwo",
        "password": "",
        "first_name": "",
        "last_name": "",
        "email": "",
        "active": "",
        "auth_token": ""
    }
]

控制台显示状态码 200 并显示所有请求的数据,类似于:

[Object, Object]
> 0
    user_id: "1"
    username: "userone"
    password: ""
    first_name: ""
    last_name: ""
    email: ""
    active: "1"
    auth_token: ""
    __proto__: Object
> 1
    user_id: "2"
    username: "usertwo"
    password: ""
    first_name: ""
    last_name: ""
    email: ""
    active: "1"
    auth_token: ""
    __proto__: Object

我所有的数据绑定都很完美,只是比较而已。我的 for 循环或 if 语句不正确吗?

4

1 回答 1

2

抱歉,如果我不理解您的问题,但应该

for (var i = 0; i < $scope.createAccount.length; i++) {
    if ($scope.createAccount[i].username == inValue) {
        console.log("Username matches existing!!");
    }
}

真的是

for (var i = 0; i < $scope.activeusers .length; i++) {
    if ($scope.activeusers [i].username == inValue) {
        console.log("Username matches existing!!");
    }
}

用 activeusers 替换 createAccount

于 2013-06-12T14:32:06.320 回答