你的垃圾箱有一些錯誤。 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
我做了很多工作。輪到你工作:瞭解發生了什麼事。如果你不太瞭解,不要改進這些代碼。
非常感謝,我欠你一個禮物?但我有兩件事要問。爲什麼你使用Math.abs,我沒有這樣做,我也該如何展示書籍,儘管我能夠提醒這本書,並將其推入數組中。 http://jsbin.com/UBIwOsE/10/ – Mike
我已經更新了我的回覆。順便說一句,Math.abs()不是必需的,這只是我的習慣。 (它確保價格不是負數) – Utopik
謝謝噸。只是一個小竅門,爲什麼不會我的bin追加一個br標記到http://jsbin.com/UBIwOsE/13/ 也爲什麼這個工作$ scope.books = $ scope.books.concat(product)但是這不是$ scope.books。的concat(產品); – Mike