2013-10-19 51 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>