很好地通过ng-click传递一个php变量但是我怎么能通过ng-click函数传递完整的php对象我已成功通过JavaScript对象但我无法通过php对象任何帮助将不胜感激。这是我的剧本:
<ul>
<!-- Retrieving of main products -->
<?
if(isset($products)):
foreach($products as $row):
?>
<li>
<a href="products/<?=$row->sub_c_id?>/<?=$row->pid?>" class="title colr"><?=$row->pname?></a>
<a href="products/<?=$row->sub_c_id?>/<?=$row->pid?>" class="thumb">
<img src="<?php echo base_url(); ?>uploads/<?=$row->product_pic?>" style="width:157px; height:181px;" alt="" />
</a>
<div class="prodbuttons">
<p class="price bold"><?=$row->pprice?></p>
<a class="cart upper" ng-click="addtocart(<?=$row->pid?>,'<?=$this->session->userdata('session_id'); ?>','<?=$row->pname?>',<?=$row->pprice?>,<?=$row->pquantity?>,<?=$row->sub_c_id?>,'<?=$row->product_pic?>','<?=$row->color?>','<?=$row->size?>',1)">Add to Cart</a>
<a ng-click="check(<? json_encode($row) ?>)">email me</a>
</div>
</li>
<? endforeach; endif; ?>
</ul>
我也尝试过这样但它也给了我错误:
<a ng-click="check(<? echo json_encode($row) ?>)">email me</a>
Angular js脚本:
$scope.addtocart=function(pid,current_session_id,pname,pprice,pquantity,sub_c_id,product_pic,color,size,qty){
$scope.errors.splice(0, $scope.errors.length); // remove all error messages
$scope.msgs.splice(0, $scope.msgs.length);
$http.post('/product/ng_insertincart', { pid : pid, current_session_id : current_session_id, pname : pname, pprice : pprice, pquantity : pquantity,sub_c_id : sub_c_id,product_pic : product_pic,color : color,size : size, qty : qty}
).success(function(data, status, headers, config) {
if (data.msg != '')
{
$scope.msgs.push(data.msg);
console.log(data);
}
else
{
$scope.msgs.push(data.msg);
}
}).error(function(data, status) { // called asynchronously if an error occurs
// or server returns response with an error status.
$scope.errors.push(status);
});
}
$scope.check=function(argument) {
console.log(argument);
}
答案 0 :(得分:1)
让人惊讶。既然你的客户端以某种方式迫使你这样做,那么至少将php内容移动到你的角度控制器。类似的东西:
var controller = function()
{
<?php
// Convert product objects to array then encode as json
$items = array();
foreach($products as $product) {
$item = array(
'pid' => $product->pid,
'pprice' => $product->pprice,
...
$items[] = $item;
}
$productsJson = json_encode($items);
?>
$scope.products = angular.fromJson('<?php echo $productsJson; ?>');
现在您的控制器中有一个合适的产品阵列,您可以在模板中使用良好的重复数据。但即使将$ products转换为json字符串也不需要在模板中完成。在你的主要PHP代码中执行它然后只是将字符串传递给模板。还有一些序列化程序可以帮助将php对象转换为数组:http://symfony.com/doc/current/components/serializer.html
答案 1 :(得分:0)
您可能需要将对象输出为正在执行的json,但要确保将其作为字符串传递给作用域函数,方法是在其周围放置单引号:
<a ng-click="check('<? echo json_encode($row) ?>')">email me</a>
然后在你的函数中:
$scope.check = function(obj) {
obj = angular.fromJson(obj);
// do something
}