3

我正在从 JSON 数据源将一组用户拉入我的 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>
4

4 回答 4

2

你可以吃:

  1. 在加载用户之后执行:

    $http.get('users').success(function(data) { $scope.users = data; $scope.user.amplification() = function() { return $scope.user.data / $scope.user.数数; } });

并用作{{user.amplification()}}

  1. 控制器的任何位置:

    $scope.$watch('user', function() { $scope.userAmplification = $scope.user.data / $scope.user.count; }, true); $http.get

  2. 或者如果 user.data/count 不变,则与 1 相同,但静态计算:

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

并且OrderBy可以用于任何表达式(不包括其他过滤器的结果)

于 2013-01-23T21:05:12.923 回答
1

如果您不需要amplicification()在更新时更新函数datacount属性user,则可以在控制器中执行以下操作:

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

    user.amplification = function() {

        return user.data / user.count;

    };

});
于 2013-06-24T21:09:15.427 回答
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()”构造函数。

于 2013-06-26T19:29:07.663 回答
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>
于 2014-06-28T11:17:20.293 回答