javascript - 从 NodeJS 获取对象到 AngularJS

标签 javascript angularjs

我在后端有一个对象。这就是我将这些对象发送到 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/

相关文章:

angularjs - 如何将 Angular-Cache 与 AngularJS 本地存储模块结合使用

javascript - Angular X-Editable 使可编辑字段出现在下一个表格单元格中

javascript - 使用 javascript 创建动画信号栏

javascript - 使用javascript在Enter键上提交表单

javascript - regenerator-runtime npm 包用于什么?

javascript - 在鼠标悬停在另一个元素上时更改 span 元素的 CSS 类

javascript - TypeError : this. props.function 不是函数

javascript - 对一些常见元素进行模态重构

javascript - 如何以函数作为参数向动态生成的元素添加 Angular 属性?

html - 样式化选定的 AngularUI 单选按钮