对 ng-repeat 项目执行简单算术并更新控制器

Perform simple arithmetic on ng-repeat items and update the controller

我是 angular 的新手,非常感谢您的帮助 我需要以下方面的帮助: 1.我有以下代码

<tr ng-repeat="user in page ">
                <td class="tdContactsCentered">{{user.name}}<input type="hidden" name="cid" value="{{user.id}}" /></td>
                <td class="tdContactsCentered" >{{user.accountNumber}}</td>
                <td class="tdContactsCentered">{{user.serialNumber}}</td>
                <td class="tdContactsCentered"><input type="text" ng-model="sdate" class="input-small" /> </td>
                <td class="tdContactsCentered"><div class="input-append">
                    <input type="text"  ng-model="ads.value"  class="input-small" />
                </div></td>
                 <td class="tdContactsCentered"><div class="input-append">
                    <input type="text"
                           ng-model ="ads.multipliedByIt"
                           class="input-small"
                           name="expected"
                          />
                </div></td>

我从我的控制器设置了 sdate 值并且它很好

下面是我的 angular 代码。

   $scope.ads = {
        value:0,
        multipliedByIt:0
};

var multipliedByIt = function() {
    $scope.ads.multipliedByIt = $scope.ads.value * $scope.sdate;
}


    $scope.$watch('ads.value',multipliedByIt );

问题是,ads.value 和 ads.multipliedByIt 绑定到 table 中的所有 cells/rows 并为它们设置相同的值,但我想为 ads.value.

我不确定我是否适当地格式化了这个问题,我希望它足够清楚。

谢谢

https://github.com/angular/angular.js/wiki/Understanding-Scopes

当您使用 ng-repeat 时,请使用 $scope.$parent 修改子范围之外的值。

试试这个:

$scope.ads = {
    value:0,
    multipliedByItself:0
};

var multipliedByIt = function(newValue, oldValue) {
    $scope.ads.multipliedByIt = newValue * $scope.sdate;
}

$scope.$watch('ads.value', multipliedByIt );

听起来你想做的是这样的:

http://codepen.io/robertmesserle/pen/16d97c19d97eb2acf339569565e5dd11?editors=001

与其依赖 Angular 为每个用户创建数据的本地副本,我建议您自己动手:

$scope.$watch('page', function (newValue, oldValue) {
  angular.forEach(newValue, function (user) {
    if (!user.ads)   user.ads = angular.extend({}, $scope.ads);
    if (!user.sdate) user.sdate = $scope.sdate;
    user.ads.multipliedByIt = user.ads.value * user.sdate;
  });
}, true);

这有几件事:

  1. 如果你的用户对象上没有ads对象,它会根据$scope.ads
  2. 添加一个
  3. 如果您的用户对象上没有 sdate 对象,它会从 $scope
  4. 复制它的值
  5. 它完成了您的旧观察者的工作

最后一部分有效,因为我将 true 传递给了 $watch 方法,告诉它对更改进行深入检查,这将像您之前那样捕获对 user.ads.value 的更改观察者。

希望对您有所帮助。


编辑:添加此内容以回应您的后续问题。这应该可以解决您的问题:

$scope.zoneConfig = function (accountForm) {
  $scope.lastAction = 'create';
  $scope.uri = "/phoenix/protected/users/conf/";
  var uri = $scope.uri;
  angular.forEach($scope.page, function (user, key) {
    var xsrfi = $.param({
      'monthlyContributable' : user.ads.value,
      'expectedAmount': user.ads.multipliedByIt
    });
  });
};

失败的原因是没有 $scope.user - $scope.page 包含一系列用户。由于您正在迭代 $scope.page,我将 value 更改为 user 以便更清楚一点,然后直接引用它。