【发布时间】:2015-01-20 21:34:51
【问题描述】:
我正在尝试使用 AngularJS 作为我的前端和 Laravel 作为我的后端来创建一个单页应用程序。我在尝试创建需要访问与另一个模型的关系的表时遇到了问题。
对于此示例,假设我有一个显示产品的表格。每个产品也会有一个品牌。
使用 Laravel 的刀片语法,我将通过以下方式解决这个问题:
<table class="table table-bordered">
<tr>
<th>Name</th>
<th>Brand</th>
</tr>
@foreach($products as $product)
<tr>
<td>{{ $product->name }}</td>
<td>{{ $product->brand->name }}</td>
</tr>
@endforeach
<!-- End of product entry for {{ $product.name }} -->
</table>
使用 Angular,我希望我能做到这一点:
<table class="table table-bordered">
<tr>
<th>Name</th>
<th>Brand Id</th>
</tr>
<tr ng-repeat="product in products">
<td>@{{ product.name }}</td>
<td>@{{ product.brand.name }}</td>
</tr>
<!-- End of product entry for @{{ product.name }} -->
</table>
很遗憾,@{{ product.brand.name }} 不起作用,而且似乎没有一种简单的方法可以访问父关系。
仅供参考,我的控制器如下所示:
app.controller('CtrlProducts', function($scope, $http){
$scope.products = [];
$http.get('/api/products').
success(function(data, status, headers, config) {
angular.forEach(data, function(product){
$scope.products.push(product);
});
}).
error(function(data, status, headers, config) {
console.log(data);
});
});
我能想到的唯一解决方案是对 Brand 模型进行单独的 api 调用并将数据存储到地图对象中。然后我可以打电话:@{{ brandMap.get(product.brand_id) }}
有人知道更简单的解决方案吗?似乎这将是一个常见的问题。
谢谢。
【问题讨论】: