【发布时间】:2015-09-08 11:25:00
【问题描述】:
我正在尝试从我使用 Angular 的 $http.get() 函数填充的 js 数组中列出 DOM 中的一些产品。
来自 php 的 JSON 回复工作正常,我 console.log 将数据及其 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>
我尝试在控制器内部创建一个 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 字符串。
【问题讨论】:
-
为什么会有
PHP标签?对我来说,这似乎是一个 JS 问题,因为没有涉及 PHP 代码。 -
我在 html 中看到了 cart.products 的使用,但没有看到 products。对吗?
-
@vinayakj 我理解异步主题,虽然我正在尝试使用 Angular 的数据绑定“魔法”
-
@ArthurFrankel 是的,但是访问 products 数组的方法是使用我们的购物车对象......?不是产品本身
-
我已经尝试过使用 $scope 和 this,但没有结果......
标签: javascript html json angularjs