角度表达式中的函数在参数更改时不更新

时间:2015-04-08 12:55:28

标签: javascript angularjs

以下是我正在尝试做的简化示例。

(function(){
  var app=angular.module('Tester',[]);
  
  app.controller('TestController',function($scope){
    $scope.days=[{name:'Sun'},{name:'Mon'},{name:'Teu'},{name:'Wed'},{name:'Thu'},{name:'Fri'},{name:'Sat'}];
    //if I is use `days=['Sun','Mon'...]` it works
    $scope.values={};
    $scope.add=function(values){
      var sum=0;
      $scope.days.map(function(v){
        v=values[v];
        if(v){
          sum+=(v-0);
        }
      });
      return sum;
    }
  });
  
  app.filter('sum',function(){
    return function(obj){
      var total=0;
      for(var v in obj){
        total+=(obj[v]-0)||0;
      }
      return total;
    }
  });
})()
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="Tester">
  <div ng-controller="TestController as test">
    <input ng-model="values[day.name]" value="{{values[day.name]||0}}" ng-repeat="day in days">
    <div>{{add(values)}}</div>
    <div>{{values | sum}}</div>
  </div>
</div>

基本上我想要一排输入和总计来显示总和。如果我使用days=['Sun','Mon'...]或过滤器,它会起作用。但是过滤器在语义上似乎不正确,并且不允许我向值对象添加其他属性(value={'Mon':2,'time':123456789}会给出不正确的总和)并且days=[{name:'Sun'}...]允许我存储比days=['Sun','Mon'...]更多的信息关于每一天。

1 个答案:

答案 0 :(得分:1)

您需要稍微修改add功能,在内部v=values[v]功能中将v=values[v.name]更改为map

这是因为您的days数组现在包含对象({name: 'Mon'}等),所以......

$scope.days.map(function (v) {
  // in here v = {name: 'Mon'}, not 'Mon' as previously, 
  // but the values object still has day names as keys:
  // {'Sun': 2, 'Mon': 1} etc.
  // --> values[v] === undefined, but values[v.name] matches
})

以下是编辑的位置,它可以正常工作,因为我认为你希望它能够正常工作。哦,我在总和计算中添加了相同的(v-0)||0技巧,因此输入无效数据(例如文本)并不会将其分解。

&#13;
&#13;
(function(){
  var app=angular.module('Tester',[]);
  
  app.controller('TestController',function($scope){
    $scope.days=[{name:'Sun'},{name:'Mon'},{name:'Teu'},{name:'Wed'},{name:'Thu'},{name:'Fri'},{name:'Sat'}];
    //if I is use `days=['Sun','Mon'...]` it works
    $scope.values={};
    $scope.add=function(values){
      var sum=0;
      $scope.days.map(function(v){
        v=values[v.name];
        if(v){
          sum+=(v-0)||0;
        }
      });
      return sum;
    }
  });
  
  app.filter('sum',function(){
    return function(obj){
      var total=0;
      for(var v in obj){
        total+=(obj[v]-0)||0;
      }
      return total;
    }
  });
})()
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="Tester">
  <div ng-controller="TestController as test">
    <input ng-model="values[day.name]" value="{{values[day.name]||0}}" ng-repeat="day in days">
    <div>{{add(values)}}</div>
    <div>{{values | sum}}</div>
  </div>
</div>
&#13;
&#13;
&#13;