我在后端有一个对象。这就是我将这些对象发送到 html 的方式
res.render('product', {title:title, allCategories : allCategories, product : product[0]})
我需要将产品对象发送到 angularJs,以便我可以用它进行一些操作。产品有多种颜色。我需要使用 angularjs 在下拉菜单中列出它们。
<div id='image' ng-controller="productColor">
<select>
<option value="color" ng-repeat="color in colors">{{color}}</option>
</select>
</div>
这是我的 angularjs
var app = angular.module('product', []);
app.controller('productColor',['$scope', '$http', function($scope,$http) {
var url = 'http://localhost:3000/mens/mens-clothing/mens-clothing-suits/25604524'
$http.get(url).then(function(response) {
$scope.colors = response.product
console.log(response.product)
});
}]);
那个网址是我编的。但是当我访问该网址时,第一部分开始。
谢谢
-编辑:response.product 返回未定义
最佳答案
在您的 Angular 代码中,您正在创建一个数组,该数组在其第一个索引处有一个数组:
$scope.colors = [
response.product.colors
]
将该位更改为
$scope.colors = response.product.colors;
它应该适合你:
app.controller('productColor',['$scope', '$http', function($scope,$http) {
var url = 'http://localhost:3000/mens/mens-clothing/mens-clothing-suits/25604524'
$http.get(url).then(function(response) {
console.log(response.data)
console.log(response.product)
$scope.colors = response.product.colors;
});
}]);
<div id='image' ng-controller="productColor">
<select>
<option value="color" ng-repeat="color in colors">{{color}}</option>
</select>
</div>
您当前正在尝试使用此代码将数据以 JSON 形式发送到您的 Angular 脚本:
res.render('product', {title:title, allCategories : allCategories, product : product[0]})
但这不会创建 JSON 格式的响应。正如 Express 文档所说:
Renders a view and sends the rendered HTML string to the client.
您要使用的是 res
对象的 json()
方法
Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().
代码如下所示:
res.json({title:title, allCategories:allCategories, product:product[0]});
关于javascript - 从 NodeJS 获取对象到 AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49114946/