我正在尝试从我使用 Angular 的 $http.get() 函数填充的 js 数组中列出 DOM 中的一些产品。
来自 php 的 JSON 回复工作正常,我控制台记录数据及其 JSON 格式,但 Angular 没有检测到这个......
我的 JS 代码:
var app = angular.module("system", []);
var base = "http://localhost/web";
app.controller("CartController", ['$http', function($http){
$http.get(base+'/store/getCartProducts').
success(function(data,status,headers,config){
this.products = data.products;
}).
error(function(data,status,headers,config){
console.log("Error: " + data);
});
this.remove = function(item){
var id = item.id;
var index = this.products.indexOf(item);
this.products.splice(index,1);
};
}]);
我的 HTML 代码是:
<div ng-controller="CartController as cart" >
<table>
<tbody>
<!-- CART ITEMS -->
<tr ng-repeat="item in cart.products" ng-show="cart.products.length">
<td><img class="cart-bot-icon" ng-src="{{item.icon}}" ></td>
<td class="cart-product-title">{{item.title}}</td>
<td><span class="green-price">{{item.price | currency}}</span></td>
<td>
<a href ng-click="cart.remove(item)">
<span class="glyphicon glyphicon-trash delete-cart-item"></span>
</a>
</td>
</tr>
</tbody>
</table>
</div>
我尝试在 Controller 中创建一个 this.loadProducts
函数,并在 div 上的 ng-init
上调用它,但它没有加载它们。
我打印了我的 products
数组的长度,它显示得很完美。
我已经尝试初始化 this.products = null
然后通过调用 this.loadProducts 来填充它......
还尝试了 $scope.products = []
和 $scope.products = null
什么也没有....没有想法 =/
编辑 1:
更改为使用 this
而不是 $scope
。当我在成功方法中打印出 data
时,我得到 [object Object],正确的 JSON 对象。我还 JSON.stringify(data)
并得到一个带双引号的 JSON 字符串。
最佳答案
你必须使用 this.products
。当您使用 Controller As
语法时,没有 $scope
。
要进行调试,请尝试以下操作:
在您的 success(function (...) { ... })
中,添加行 console.log("Data:", data);
。
然后在您的 HTML 中添加行 {{cart.products}}
以查看是否绑定(bind)了任何内容。
我怀疑 ng-repeat 存在显示问题。我周五回答了一个类似的问题,用户也遇到了同样的问题。您从服务器获得的响应很可能被解释为字符串,而不是对象。
您可能必须将它从字符串转换为 json:JSON.parse(data.products);
我认为问题是您的服务器返回的 JSON 无效。例如,如果它使用单引号而不是双引号,那将是无效的 JSON。
关于javascript - 使用 JSON 填充 js 数组时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30989626/