AngularJS : 通过 id 从工厂获取对象

AngularJS : get object by id from factory

我有一个 factory 可以从数据库中获取包含我所有客户的数组。 然后我需要按人过滤此数组 id 并仅在单个页面中显示它的数据。

我已经有了一个工作代码,但它只在 controller 中,我想将它与 factorydirective 一起使用,因为我不再使用 ng-controller 并且这个 factory 已经调用了我需要显示客户数据的其他页面。

这就是我尝试用 factory 做的事情:

app.js

app.factory('mainFactory', function($http){

    var getCliente = function($scope) {
        return $http.get("scripts/php/db.php?action=get_cliente")
        .success( function(data) {
            return data;
        })
        .error(function(data) {
        });
    };

    var getDetCliente = function($scope,$routeParams) {
        getCliente();
        var mycli = data;
        var myid = $routeParams.id;
        for (var d = 0, len = mycli.length; d < len; d += 1) {
            if (mycli[d].id === myid) {
                return mycli[d];
            }
        }
        return mycli;
    };

    return {
        getCliente: getCliente,
        getDetCliente: getDetCliente
    }
});

app.directive('detClienteTable', function (mainFactory) {
    return {
        restrict: "A",
        templateUrl: "content/view/det_cliente_table.html",
        link: function($scope) {
            mainFactory.getDetCliente().then(function(mycli) {
                $scope.pagedCliente = mycli;
            })
        }
    }
});

detClient.html

<p>{{pagedCliente.name}}</p>
<p>{{pagedCliente.tel}}</p>
<p>{{pagedCliente.email}}</p>
[...more code...]

问题是,我无法在页面中显示任何数据,而且我的控制台也没有错误。

可能出了什么问题?
请记住我正在学习 AngularJS.

您将 getCliente 视为 getDetCliente 中的同步调用。有趣的是,在您的指令中,您了解到 getDetCliente 是异步的。将getCliente改成这样,在getDetCliente:

中调用时将其视为异步调用
var getCliente = function($scope) {
    return $http.get("scripts/php/db.php?action=get_cliente");
};

基本上你需要实现一个承诺链,因为查看你的代码看起来你正在携带 getCliente() 承诺到 getDetCliente 方法。在这种情况下,您需要使用 .then 函数而不是使用 .success & .error ,这不允许您继续承诺链。在 getDetCliente 函数之后,您再次需要使用 .then 函数,该函数在 getCliente 函数得到解决他的承诺时被调用。您的代码将使用 form it 和 return mycli 结果重新格式化它。

代码

var getCliente = function() {
    return $http.get("scripts/php/db.php?action=get_cliente")
    .then( function(res) { //success callback
        return res.data;
    },function(err){ //error callback
       console.log(err)
    })
};

var getDetCliente = function(id) {
    return getCliente().then(function(data){
        var mycli = data;
        var myid = id;
        for (var d = 0, len = mycli.length; d < len; d += 1) {
           if (mycli[d].id === myid) {
              return mycli[d];
           }
        }
        return mycli;
    })
};

编辑

你不应该将控制器 $scope 传递给将与你的指令和控制器紧密耦合的服务,你还想传递路由的 id 参数,那么你需要传递它来自指令服务调用

link: function($scope) {
    mainFactory.getDetCliente($routeParams.id).then(function(mycli) {
        $scope.pagedCliente = mycli;
    })
}