TypeError:无法读取未定义的属性“对象”

时间:2014-03-10 07:39:51

标签: javascript angularjs

我收到此错误TypeError: Cannot read property 'objects' of undefined 我想迭代throw数组,找到当前的id。我想我不能在服务中使用$scope?如何正确定义$scope

我使用http GET方法从工厂获得的对象。

app.service('sharedService', function (Inventory, User, Tags) {

var allInventories = Inventory.query();
var allTags = Tags.query();
var allUsers = User.query();

return {

    getInventory: function() {
        return allInventories;
    },
    setInventory: function(inventoryValue){
        allInventories = inventoryValue;
    },
    getTags: function() {
        return allTags;
    },
    setTags: function(TagsValue){
        allTags = TagsValue;
    },  
    getUser: function(){
        return AllUsers;
    },
    setUser: function(UserValue){
        allUsers = UserValue;
    },

    findById: function findById($scope, id) {
                    for(var i = 0; i < $scope.info.objects.length; i++){
                        if($scope.info.objects[i].id == id){
                            return $scope.info.objects[i];
                        } 
                    }
                    return null;
                }
    };

 });

1 个答案:

答案 0 :(得分:1)

您可以传递Info对象,而不是传递范围,这将分离您的服务和控制器。

 findById: function findById(info, id) {
                    for(var i = 0; i < info.objects.length; i++){
                        if(info.objects[i].id == id){
                            return info.objects[i];
                        } 
                    }
                    return null;
                }
    };

然后在控制器中使用正确的参数

调用此方法
sharedService.findById($scope.info);

并确保在success调用的$http事件中调用此函数,因为您从http GET方法获取此数据。