angular.js - 购物车中删除一条数据,总价没有跟着变动?
大家讲道理
大家讲道理 2017-05-15 17:05:28
0
2
510

在学习用angular做购物车功能时,遇到一个问题:
我在删除一条商品时,总价没有跟着变动,折腾了几天,实在琢磨不出,请大家帮忙看看,谢谢大家了

    To Do List      
namepricetotaldel
{{z.name}} {{z.total}} {{z.price}} {{z.total * z.price}} delted
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all (2)
漂亮男人

Add a function

function totalPrize(){ var total=0; angular.forEach($scope.todo2,function(item,index){ total+=item.price*item.total; }) $('.total').text(total); }

and the del function is changed to

$scope.del = function(id) { // alert($scope.todo2.length) $scope.todo2.splice(id,1) totalPrize(); }

I have to complain that your current code doesn’t look like you’re writing in Angular at all, it’s still at the jQuery level. Reducing DOM operations is the original intention of Angularjs, but you directly use the .text() method to assign values. Why not just bind total to $scope and just {{total}} on html.
In addition, it is not advisable to place the array model2 directly outside to pollute the global variables. You can also put the initialization init code in the controller. There is no need to init in html.

Deleting elements in the array, there is no reason for the total price to change. Firstly, the total price is not bound to the scope. Furthermore, even if the total price variable is bound to the scope, it is also a primitive data type. After each operation, you need to To get the total price, you have to calculate it again.

    To Do List   
name price total {{total}} del
{{z.name}} {{z.total}} {{z.price}} {{z.total * z.price}} delted

Insert a piece of my code. There are many things that can be optimized, but I have to go for a run and don’t have time to change it. If you want to use it, pay attention to the path of importing js and css files

    phpcn_u1582

    If you use jQuery directly to modify the VIEW layer or MODEL layer data, you need to manually synchronize the data.
    You can use as needed:

    $scope.$digest()

    or

    $scope.$apply(function(){ //do sth here. })

    To sync data. For details, please refer to AngularJS API

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!