【发布时间】:2017-03-22 12:46:41
【问题描述】:
我对 Angular JS 比较陌生。目前我遇到了一个问题,假设我的列表中有 1000 个项目。为了显示每个项目的详细信息,我将传递 items_id 以生成 html 示例(123.html)。在这种情况下,我需要1000个控制器来处理这种情况吗?
控制器
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>
【问题讨论】:
-
绝对不是,只有一个视图和控制器,并使用查询字符串或路径变量在控制器内部处理。
-
@imprezzeb 感谢您的快速回复。但这是否意味着我仍然需要创建 1000 个不同的 ID html 文件但只有一个控制器?
-
不只是定义单一视图(HTML)。
-
不是我的头,但阅读自定义元素/指令会很有用。将在标记中写入
<customProduct pid="numberAsNgRepeatVarHere"></customProduct>的内容。然后你会在数组中的每个产品编号上或周围放置一个 ng-repeat。最后,我认为从控制器进行实际调用是一种反模式——可能创建一个接受 pid 并进行实际调用的“getProduct”服务,并通过承诺或东西。 -
是的,我同意@anied,使用工厂来定义你所有的 http 调用,并在你的控制器中使用该服务/工厂方法。
标签: javascript angularjs