javascript - 使用 ng-repeat 在每次重复中调用函数

标签 javascript angularjs

我有以下关系:类别<--->产品(具有1-N基数)

这是 html 表格中的 ng-repeat 指令

<tr ng-repeat="category in categories">
    <td>{{category.name}}</td>
    <td>{{products[category.id]}}</td>
</tr>

所以我需要做的是,每次重复列出一个类别时,该类别将立即发送到 getAllProductsByCategory() 函数,然后 $http 服务将获取该类别的所有产品属于这个特定类别。

我尝试使用ng-init指令来执行该函数,但我认为这不是正确的使用方法。有更好的方法吗?

<tr ng-repeat="category in categories" ng-init="getAllProductsByCategory(category)">
    <td>{{category.name}}</td>
    <td>{{products[category.id]}}</td>
</tr>

这个函数将按类别获取所有产品

$scope.getAllProductsByCategory = function(category){
$http("getAlProductsByCategory"+category.id){
    .success(function (data, status, headers, config) {
        $scope.products[category.id] = data;
    })
    .error(function (data, status, header, config){
        $log.error("Error");
    });
}

最佳答案

I don't know how to split an array in the controller in order to pass every object to the getAllProductsByCategory(category)

我不建议使用 ng-init 来调用异步 API。在模型 View 架构中,模型应该驱动 View 。 View 不应驱动模型。 View 可以收集 Controller 的用户输入事件。然后, Controller 可以使用这些事件来更新模型,如有必要,还可以使用异步 API。

在这种情况下,类别列表可能来自异步 API,那么每个类别的产品都需要来自异步 API。这可以通过chaining promises来完成。 .

首先创建一个类别 promise :

var categoriesPromise = $http.get(categoriesUrl)
  .then(function (response) {
    var categories = response.data;
    $scope.categories = categories;
    //return to chain categories
    return categories;
}).catch(function (error) {
    console.log("ERROR: ", error.status);
    //throw to chain rejection
    throw error;
});

现在就兑现这个 promise :

$scope.products = {};

var productsPromise = categoriesPromise.then(function(categories) {
    var promiseHash = {};
    categories.foreach(function(c) {
        promiseHash[c.id] = getProductsByCategory(c)
          .then(function(products) {
             $scope.products[c.id] = products;
             //return data for chaining
             return products;
        });
    });
    //return $q.all promise for chaining
    return $q.all(promiseHash);
});

欲了解更多信息,请参阅

关于javascript - 使用 ng-repeat 在每次重复中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41076424/

相关文章:

javascript - Mongoose 模型中的 model 和 model._doc 有什么区别?

javascript - 调试 Protractor 到 Angular 同步问题的规范方法

angularjs - Angular 什么时候销毁指令实例?

javascript - 您如何以编程方式确定 HTML 对象可以监听哪些事件?

javascript - 如何组织多个文件中的 View

javascript - 将 id 添加到输入

javascript - 为什么数组将一个空数组插入另一个数组?

javascript - AngularJSgreetController Controller 不工作

javascript - 如何在发出 http 请求之前对复选框点击进行排队?

angularjs - Angular Directive 的模板绑定(bind)不会更新