首页 > javascript > angularjs指令丢失数组格式过滤器

angularjs指令丢失数组格式过滤器 (angularjs directive losing array format filter)

问题

我试图在指令中进行简单的数组排序。但不知何故,当我将嵌套数组放入orderBy过滤器时,它会丢失数组并成为一个对象(无法排序)

当我在指令中注销scope.item时它会说:addresses:Array [2]

但是在尝试使用$ filter('orderBy')(scope.item.addresses,'distance')进行过滤时; 我得到“TypeError:对象不是一个函数”

(function(angular){
'use strict';
angular.module('starter').directive('getDistance', function() {
    return {
        restrict: 'E',
        replace: true,
        link: function (scope, element, $filter) {

            ;
            console.log(scope.item);

            scope.item.addresses = $filter('orderBy')(, scope.item.addresses, 'distance');

            console.log(scope.item.addresses);
        }
    };
});
})(window.angular);

解决方法

您需要inject在指令定义中过滤而不是在链接函数中。

angular.module('starter').directive('getDistance', function($filter) {

要么

angular.module('starter').directive('getDistance', ['$filter', function($filter) {..

和(删除额外的逗号,这可能是一个错字):

scope.item.addresses = $filter('orderBy')(scope.item.addresses, 'distance');

问题

I am trying to do a simple array sort in a directive. But somehow when i put the nested array in the orderBy filter it is losing array and becomes an object (which can not be ordered)

when i log out the scope.item inside the directive it says: addresses: Array[2]

but when trying to filter using $filter('orderBy')(scope.item.addresses, 'distance'); i am getting "TypeError: object is not a function"

(function(angular){
'use strict';
angular.module('starter').directive('getDistance', function() {
    return {
        restrict: 'E',
        replace: true,
        link: function (scope, element, $filter) {

            ;
            console.log(scope.item);

            scope.item.addresses = $filter('orderBy')(, scope.item.addresses, 'distance');

            console.log(scope.item.addresses);
        }
    };
});
})(window.angular);

解决方法

You need to inject filter in the directive definision not in the linking function.

angular.module('starter').directive('getDistance', function($filter) {

Or

angular.module('starter').directive('getDistance', ['$filter', function($filter) {..

and do (Removing the extra comma, which probably is a typo):

scope.item.addresses = $filter('orderBy')(scope.item.addresses, 'distance');
相似信息