角度重用控制器功能作为自定义orderBy函数

时间:2014-10-30 10:58:06

标签: javascript angularjs angularjs-ng-repeat angularjs-orderby

我有一个像这样的控制器:

var moduleFichiersDupliques = angular.module('fichiersDupliques', []);

moduleFichiersDupliques.controller("FichiersDupliquesController", [ '$http', '$log', function($http, $log) {

    var store = this;

    $http.get('groupes-dupliques-data.json').success(function(data) {
        store.groupesDupliquesData = data;
    });

    this.getNombreFichiersDansGroupe = function(groupe) {
        return groupe.fichiers.length;
    };

    this.getTailleFichier = function(groupe) {
        return groupe.tailleTotale / this.getNombreFichiersDansGroupe(groupe);
    };

    this.getTailleGaspillee = function(groupe) {
        var tailleGaspillee = groupe.tailleTotale - this.getTailleFichier(groupe);
        return tailleGaspillee;
    };
}]);

和我的html代码中的ng-repeat

<td ng-repeat="groupe in fichiersDupliquesCtrl.groupesDupliquesData | orderBy:fichiersDupliquesCtrl.getTailleGaspillee:true">
{{fichiersDupliquesCtrl.getTailleGaspillee(groupe)}}
</td>

我收到了这个错误:

TypeError: Cannot read property 'getTailleFichier' of undefined
at getTailleGaspillee (/test/js/fichiersdupliques.js:26:58)
at Array.<anonymous> (/test/js/angular-1.3.0.js:17321:24)
at comparator (/test/js/angular-1.3.0.js:17330:36)
at /test/js/angular-1.3.0.js:17337:34
at Array.sort (native)
at /test/js/angular-1.3.0.js:17326:22
at $parseFilter (/test/js/angular-1.3.0.js:11939:19)
at Object.interceptedExpression (/test/js/angular-1.3.0.js:12579:21)
at Scope.$digest (/test/js/angular-1.3.0.js:13957:40)
at Scope.$apply (/test/js/angular-1.3.0.js:14227:24) 

如何重构我的代码,以便可以在自定义orderBy函数和我的html页面中使用此函数?

1 个答案:

答案 0 :(得分:0)

您将要使用$scope

替换:

<td ng-repeat="groupe in fichiersDupliquesCtrl.groupesDupliquesData | orderBy:fichiersDupliquesCtrl.getTailleGaspillee:true">
    {{fichiersDupliquesCtrl.getTailleGaspillee(groupe)}}
</td>

使用:

<td ng-repeat="groupe in groupesDupliquesData | orderBy:getTailleGaspillee:true">
    {{getTailleGaspillee(groupe)}}
</td>

然后为您的控制器:

moduleFichiersDupliques.controller("FichiersDupliquesController", ['$scope', '$http', '$log', function($scope, $http, $log) {
    $scope.getNombreFichiersDansGroupe = function(groupe) {
        return groupe.fichiers.length;
    };
    $scope.getTailleFichier = function(groupe) {
        return groupe.tailleTotale / $scope.getNombreFichiersDansGroupe(groupe);
    };
    $scope.getTailleGaspillee = function(groupe) {
        var tailleGaspillee = groupe.tailleTotale - $scope.getTailleFichier(groupe);
        return tailleGaspillee;
    };
}]);

这样,只要html位于fichiersDupliquesCtrl的范围内,您就不必在html中指定fichiersDupliquesCtrl
(含义,在<div ng-controller="FichiersDupliquesController">