2013-01-23 49 views
3

我从JSON数据源中将用户数组拖入AngularJS模型中。这些数据正在表格中呈现,我想创建一个从现有用户对象的两个值计算出来的列,而不修改我的基础数据服务。在AngularJS模型中向数组的每个元素添加计算字段

// My model 
function UserListCtrl($scope,$http) { 
$http.get('users').success(function(data) { 
    $scope.users = data; 
}); 
}; 

在我的部分模板,我知道我可以做这样的事情:

<tr ng-repeat="for user in users"> 
    <td>{{user.data/user.count | number:2}}</td> 
</td> 

但我想那场,而添加到模型中,这样我就可以使用它像这样:

<td>{{user.amplification}}</td> 

如何将“放大”字段添加到我的模型中的每个用户?

顺便说一句,是不是可以使用orderBy过滤器上是这样的:

<td>{{user.data/user.count | number:2}}</td> 

回答

2

可以eather:

  1. 刚过加载用户做:

    $ http.get('users')。success(function(data){scope = 0; $ scope.user.amplification()= function(){return $ scope.u ser.data/$ scope.user.count; } }); 。

    $ $范围手表( '用户',函数(){$ scope.userAmplification = $ scope.user:

而作为{{user.amplification()}}

  1. 在任何地方使用控制器.data/$ scope.user.count; },true); $ http.get

  2. 或者,如果user.data/count不改,做同样为1,但staticly计算:

    $ http.get( '用户')成功(功能(数据) $ scope.userrs = data; $ scope.user.amplification = $ scope.user.data/$ scope.user.count; });

而且OrderBy可以在任意表达式(其它过滤器的uncluding结果)

+1

$ scope.user是如何定义的?我得到未定义的错误。 – Alan

+0

我已经更新了这个问题,因为我发现之前并不清楚。 '$ scope.users'是'user'对象的数组。我想为这些“用户”对象中的每一个添加一个“放大”字段。我可以修改我的json服务来执行此操作,但是我想知道是否可以在我的控制器中执行此操作。 – Alan

+1

@Alan,您已将答案标记为正确,但我也收到您指出的未定义错误。有什么我失踪? – jwize

1

使用如果你不需要你amplicification()功能更新时,您user更新datacount属性,你可以在你的控制器中做这样的事情:

$scope.users.forEach(function(user) { 

    user.amplification = function() { 

     return user.data/user.count; 

    }; 

}); 
0

添加第二个答案,因为我觉得它适合,因为它与我的第一个不同。

稍微环顾一下后,我发现如果您尝试动态添加新行或者依赖于计算值的数组中的新元素,我最初发布的方法会落在其他位置。这是因为$scope.array.forEach()只能在控制器创建时运行。

解决此问题的最佳方法是创建一个包含所需选项的正确定义的object。例如

function Task(id, name, prop1, prop2) { 

    this.id = id; 
    this.name = name; 
    this.prop1 = prop1; 
    this.prop2 = prop2; 

    this.computedProperty = function() { 

     return this.prop1 + this.prop2; 

    }; 

} 

这比创建的每个新对象都具有新属性要灵活得多。

唯一的缺点是,在您的ajax成功回调中,您需要将每个用户传递到您的'Users()'构造函数中。

0

对我来说有效的是添加一个循环,并将该属性添加到该循环中的每个项目。我使用了控制器的一个属性,但我相信你可以按照你在问题中接近它的方式使用范围。

function(result) { 
    self.list = result; 
    angular.forEach(self.list, function(item) { 
     item.hasDate = function() { 
      return this.TestDate != null; 
     }.bind(item); // set this context 
    }); 
} 

然后在我的标记中,我只是用它这样。

<div ng-repeat...> 
    <div ng-show="item.hasDate()">This item has a date.</div> 
</div> 
相关问题