AngularJS更新对象属性

时间:2016-03-12 22:04:42

标签: angularjs

我试图在对象的angularjs数组中更新onbject的属性。

我有以下对象数组:

  $scope.formes= [
{id: 0, geo: 0,cx:0, cy:0, b:0, h:0, r:0, d:0, a:0, ax:0, ay:0, val: 0}
 ];

默认情况下,每个属性的值都设置为0,直到用户在字段中键入新值。用户添加新对象或点击按钮后会更新某些值。这个应用程序用于计算基本几何形状的中心和瞬间。只是fyi。

这是用户添加对象时正在运行的功能。

$scope.ajoutForme = function(){

     $scope.formes.a = parseInt($scope.formes.b) * parseInt($scope.formes.h); /// not working

  $scope.formes.push({
    id: $scope.nbrForme++ //just adding and new id
  });  
}

在添加objet之前,我想用计算更新一些值。例如,在这种情况下,我应该使用a设置b*h的值。

我试过

$scope.formes[nbrForme].h = parseInt($scope.formes[nbrForme].b) * parseInt($scope.formes[nbrForme].h); //This is working but only the first time I press the button??

nbrForme是=我正在处理的元素的id,当我添加一个新对象时会增加。

完成控制器

var moment = angular.module('moment',[]);
var nbrForme = 0;

moment.controller('momentCtrl', ['$scope', function($scope) {
  $scope.nbrForme = nbrForme;
  
 $scope.formes= [
{id: 0, geo: 0,cx:0, cy:0, b:0, h:0, r:0, d:0, a:0, ax:0, ay:0, val: 0}
 ];


$scope.ajoutForme = function(){

	 $scope.formes[nbrForme].a = parseInt($scope.formes[nbrForme].b) * parseInt($scope.formes[nbrForme].h); /// only work once
	
  $scope.formes.push({
	id: $scope.nbrForme++
  });  
}
}
}]);

1 个答案:

答案 0 :(得分:2)

您的对象定义错误:

$scope.object = [
    {id:0, attr1:2, attr2:4, attr3:0},
    {id:1, attr1:2, attr2:4, attr3:0},
    {id:2, attr1:2, attr2:4, attr3:0}
];

注意添加,来分隔数组的元素。

修改

你写道这行不起作用$scope.formes.a = parseInt($scope.formes.b) * parseInt($scope.formes.h); 这是因为$scope.formes是一个数组,因此您必须引用数组中具有a / b / h属性的特定对象。问题是哪一个?

如果它是数组中的第一个索引,那么

$scope.formes[0].a = parseInt($scope.formes[0].b) * parseInt($scope.formes[0].h);

最后一个元素:

var lastIndex = $scope.formes.length - 1;
if (lastIndex >= 0) {
    $scope.formes[lastIndex].a = parseInt($scope.formes[lastIndex].b) * parseInt($scope.formes[lastIndex].h);
}

如果$scope.nbrForme是您当前正在处理的元素的ID,则需要将其值减1,因为您从值1开始,并且数组的第一个索引为0 :

$scope.formes[$scope.nbrForme - 1].a = parseInt($scope.formes[$scope.nbrForme - 1].b) * parseInt($scope.formes[$scope.nbrForme - 1].h);