gpt4 book ai didi

javascript - 在单个 Controller 中处理多个项目? AngularJS

转载 作者:行者123 更新时间:2023-12-01 03:53:53 24 4
gpt4 key购买 nike

我对 Angular JS 比较陌生。目前我遇到了一个问题,假设我的列表中有 1000 个项目。为了显示每个项目的详细信息,我将传递 items_id 来生成 html 示例(123.html)。那么,我需要1000个 Controller 来处理这种情况吗?

Controller

 app.controller('item0001',function($scope,$http,$sce){
$scope.data = [];
$scope.details=[];
$http.get("https://api.com/test/product/0001").then(function(response){
var getData = response.data;
$scope.data.push(response.data);
$scope.bindHtml = $sce.trustAsHtml(getData.details);
for(var i = 0; i<getData.specification.length; i++){
$scope.details.push(getData.details[i]);
}
});
});

app.controller('item0002',function($scope,$http,$sce){
$scope.data = [];
$scope.details=[];
$http.get("https://api.com/test/product/0002").then(function(response){
var getData = response.data;
$scope.data.push(response.data);
$scope.bindHtml = $sce.trustAsHtml(getData.details);
for(var i = 0; i<getData.specification.length; i++){
$scope.details.push(getData.details[i]);
}
});
});

查看

<p>
<a href="{{items.id}}.html" role="button">View More</a>
</p>

最佳答案

使用单个 Controller 和 HTML。

将 HTML 与某些 ViewModel 绑定(bind)($scope 上的属性)

从您的 Controller 中使用服务调用以获取项目详细信息(我假设您已通过单击某个按钮获取了这些详细信息)。

在服务成功回调后更新 View 模型。和 Angular 使用 2 路绑定(bind),将使用最后获取的项目更新 View 。

Controller :

app.controller('ProductCtrl', function($scope, ProductService) {
var getProduct = function(productId) {
ProductService.getProduct(productId).then(function(response) {
$scope.productDetails = response.data;
})
};
});

服务:

app.factory('ProductService', function($http) {
return {
getProduct(productID) {
return $http({
method: 'GET',
url: "https://api.com/test/product/" + productID
});
};
}
});

HTML View :

<body ng-controller="ProductCtrl">
<div ng-init="getProduct(0001)">
<p>Name {{productDetails.name}}</p>
<p>ID {{productDetails.id}}</p>
<p>Description {{productDetails.description}}</p>
</div>
<button ng-click="getProduct(productDetails.id + 1)">Get Next Product</button>
</body>

我希望这能让您了解如何实现您的要求。请详细说明您的问题,以便我提供更具体的解决方案。

关于javascript - 在单个 Controller 中处理多个项目? AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42942517/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com