質問

I need to elaborate some functions in a ng-repeat, but i can't access the right field with the $watch function.

This is my code but prolly I access the field in a wrong way that cause me Javascript error of undefined.

.html

<body ng-controller="MainCtrl">    
<div ng-form="mainForm">
<a ng-click="addNewr1()">Add New r1</a>
<ul>
  <li ng-repeat="rb_r1 in currForm.r1" ng-form="subFormr1">
   <input type="number" step="0.1" ng-model="rb_r1.runo" name="r_runo" required />
   <input type="number" step="0.1" ng-model="rb_r1.rdue" name="r_rdue" required />
   <input type="number" step="0.1" ng-model="rb_r1.rsomma"/>
  </li>
</ul>
</div>
</body>

.js

var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function ($scope) {
  $scope.master = {};
  $scope.currForm.r1 = [];

  $scope.addNewr1 = function (){
    $scope.currForm.r1.push({ runo: 0,rdue: 0,rsomma: 0 });};
  $scope.$watch('rb_r1.runo + rb_r1.rdue', function (value) {
    $scope.rb_r1.rsomma= value;
  }, true);
 });

So I found a fiddle and modifying it I get the solution, but in a limited way, cause I had to access to the field in a static way. How can i do that in a dinamic way?

http://jsfiddle.net/fe9ws/

TY All!

役に立ちましたか?

解決 2

I resolved with a for in the $watch function..

$scope.$watch('formData.socials',
              function(value){
                  var i;
                  for(i = 0; i < value.length; i++)
                      value[i].somma = value[i].uno + value[i].due;
              }, true);   

see the fiddle! Ty all

http://jsfiddle.net/JWTE2/

他のヒント

I am still not clear on what you attempted to do but you do not need a $watch for the task described:

Since "somma" is a calculated You can define your field like this and it will produce the desire result:

 <input type="number" name="somma" value="{{social.uno + social.due}}">
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top