2013-10-19 54 views
0

我在ng-click上调用一个函数,该函数应该用来自JSON数据的值更新html。Angularjs双向数据绑定不起作用?

我不知道这应该如何工作,或者我在这里做错了什么?

我的代码如下所示:

<table class="table table-striped table-bordered"> 
      <thead class="head"> 
       <th>Product</th> 
       <th>Description</th> 
       <th>Price(Rs.)</th> 
       <th>Add to Cart</th> 
      </thead> 
      <tr ng-repeat="row in rows | filter:search | orderBy:'product'" > 
       <td>{{row.product}}</td> 
       <td>{{row.description}}</td> 
       <td>{{row.price}}</td> 
       <td><a ng-click="addToCart(price)">Add to cart</a></td> 
      </tr> 

     </table> 

下面是我的仓http://jsbin.com/UBIwOsE/2/

有人能帮助我,告诉我怎么更新与红色边框的股利。我需要用点击添加到购物车的图书名称和价格来更新它。

谢谢

回答

8

你的垃圾箱有一些错误。 1)有ng-click="{{addToChat(price)}}"。当然,应该删除{{ }}

2)你的addToCart()没有完成

我已经更新了你的bin http://jsbin.com/UBIwOsE/5/

// In your controller 

// init variables 
$scope.price = $scope.selected = 0; 

// fired with ng-click() 
$scope.addToCart = function(price) { 
    $scope.price += Math.abs(price); 
    $scope.selected++; 
} 

// In your template 

// 1) the ng-click directive looks like this 
<td><a ng-click="addToCart(row.price)">Add to cart</a></td> 

// 2) show infos 
<div class="cart"> 
    You have {{selected}} books and Total cost is {{price}} 
</div> 

它的工作原理,但它并不完美。看一看,从中学习,并了解angularjs更多的教程(我建议你看http://egghead.io视频,自由和制作精良)


问题2(从评论)

我已经更新垃圾桶http://jsbin.com/UBIwOsE/11/

<!-- template --> 

<!-- the parameter sent is the object itself (row instead of row.price) --> 
<a ng-click="addToCart(row)">Add to cart</a> 

<!-- ... -> 

    You have {{books.length}} books and Total cost is {{price}}<br /> 
<!-- ng-show shows or hides the element based on the expression. --> 
<div ng-show="books.length > 0"> 
    These books are 
    <ul> 
     <!-- ng-repeat duplicates the template for each element in the collection. --> 
     <li ng-repeat="book in books">{{book.product}} ({{book.price}})</li> 
    </ul> 
</div> 

-

// controller 

// we push the object into the array, so that we can access to all the data into the template ({{book.product}} - {{book.price}}) 
// $scope.selected is useless now. The array's length is enough 
// we keep $scope.price because it's easier than recalculating it from the array. 
$scope.addToCart = function(row) { 
    $scope.price += row.price; 
    $scope.books.push(row); 
} 

现在,您必须跟踪$scope.books中的重复元素 有很多方法可以做到这一点。我的最爱看起来像http://jsbin.com/UBIwOsE/12

我做了很多工作。轮到你工作:了解发生了什么事。如果你不太了解,不要改进这些代码。

+0

非常感谢,我欠你一个礼物?但我有两件事要问。为什么你使用Math.abs,我没有这样做,我也该如何展示书籍,尽管我能够提醒这本书,并将其推入数组中。 http://jsbin.com/UBIwOsE/10/ – Mike

+0

我已经更新了我的回复。顺便说一句,Math.abs()不是必需的,这只是我的习惯。 (它确保价格不是负数) – Utopik

+0

谢谢吨。只是一个小窍门,为什么不会我的bin追加一个br标记到http://jsbin.com/UBIwOsE/13/ 也为什么这个工作$ scope.books = $ scope.books.concat(product)但是这不是$ scope.books。的concat(产品); – Mike

1

它应该是row.priceng-click

<td><a ng-click="addToCart(row.price)">Add to cart</a></td>