Javascript 用JSON填充js数组时出现问题
我试图从我使用Angular的$http.get()函数填充的js数组中列出DOM中的一些产品 php的JSON回复工作正常,I console.log记录数据及其JSON格式,但Angular没有检测到这一点 我的JS代码:Javascript 用JSON填充js数组时出现问题,javascript,html,json,angularjs,Javascript,Html,Json,Angularjs,我试图从我使用Angular的$http.get()函数填充的js数组中列出DOM中的一些产品 php的JSON回复工作正常,I console.log记录数据及其JSON格式,但Angular没有检测到这一点 我的JS代码: var app = angular.module("system", []); var base = "http://localhost/web"; app.controller("CartController", ['$http', function($http){
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>
{{item.title}
{{item.price | currency}}
我曾尝试在控制器内创建一个this.loadProducts
函数,并在div上的nginit
上调用它,但它没有加载它们
我已经打印了我的产品
阵列的长度,它显示得非常完美
我已尝试初始化this.products=null,然后通过调用this.loadProducts填充它,但什么都没有
还尝试了$scope.products=[]
和$scope.products=null
但什么都没有……完全没有想法=/
编辑1:
更改为使用
此
而不是$scope
。当我在success方法中打印出数据时,我得到了[object object],正确的JSON对象。我还JSON.stringify(data)
得到了一个带双引号的JSON字符串。您必须使用this.products
。当您使用控制器作为
语法时,没有$scope
要进行调试,请尝试以下操作:
在success(function(…){…})
中,添加行console.log(“Data:,Data”)代码>
然后在HTML中添加{{cart.products}}
行,查看是否绑定了任何内容
我怀疑ng repeat有显示问题。周五我回答了一个类似的问题,用户也有同样的问题。您从服务器得到的响应可能被解释为字符串,而不是对象
您可能需要将其从字符串转换为json:json.parse(data.products)代码>
我认为问题在于服务器返回的JSON无效。例如,如果它使用单引号而不是双引号,那将是无效的JSON。为什么它有PHP
标记?在我看来,这似乎是一个JS问题,因为没有涉及PHP代码。我在html中看到了cart.products的使用,但没有看到products。是吗?@vinayakj我理解异步主题,尽管我试图使用Angular的数据“魔力”binding@ArthurFrankel是的,但是访问products数组的方法是使用我们的cart对象。。。。?不是产品本身我已经尝试过使用$scope和$scope,但没有结果…在回调中小心this
应该存储为变量并使用variable。产品在callbackSo中,当我在success方法中打印数据时,我得到“success:[object object]”。所以它被解释为一个JSON对象,同样,当我输入JSON.stringify(data)时,我得到一个带有双引号的JSON字符串,{{cart.products}不会打印任何东西!就在app.controller(“CartController”),['$http',function($http)之后{
,你的下一行应该是var vm=this;
。从这里开始,使用vm.products=data.products;
。当你创建一个函数时,controllerAs的这个被新函数的这个覆盖。因此这个.product
在成功(…)
未设置为控制器的范围。这就是为什么必须使用类似vm
的变量。与var index=this.products.indexOf(item);
和this.products.splice(index,1);
相同,需要将其更改为var index=vm.products.indexOf(item);
和vm.products.splice(index,1)
有关详细信息,请参阅关于控制器的部分。