我正在尝试创建一个单页应用程序,以 AngularJS 作为前端,以 Laravel 作为后端。我在尝试创建需要访问与另一个模型的关系的表时遇到了问题。
对于此示例,假设我有一个显示产品的表格。每个产品也会有一个品牌。
使用 Laravel 的 Blade 语法,我可以使用以下方法解决这个问题:
<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) }}
有谁知道更简单的解决方案?看来这将是一个常见问题。
Thanks.