0

我有一个这样的控制器:

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 页面中都可以使用此函数?

4

1 回答 1

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;
    };
}]);

这样,您不必fichiersDupliquesCtrl在任何地方指定 html,只要 html 在fichiersDupliquesCtrl's 范围内。
(意思是,在一个<div ng-controller="FichiersDupliquesController">

于 2014-10-30T11:02:42.737 回答