javascript - angular 在过滤器中从 $rootScope 调用实用函数

标签 javascript angularjs angularjs-directive

我有一个实用函数 notNull() 旨在与这样的过滤器一起使用:

 ...| filter:notNull()"

我在更多指令中需要它,这就是我将它放在 $rootScope 中的原因。

问题是我的过滤器没有被调用。我创建了一个示例 plnkr:

http://plnkr.co/edit/Nq0iLw?p=preview

有人可以帮忙吗?为什么不调用过滤器而不过滤我的项目?

附言。过滤器中的这个表达式不适用于空值:

 ...| filter:{myProp:!null}

最佳答案

[注意:更新按时间倒序排列。]

更新 2

首先,回答您的问题“为什么 ...| filter:{myProp:!null} 不起作用:
这是因为您尝试使用的语法(根据 the docs )仅适用于字符串值(并且 null 不是字符串值)。

您可以创建(并附加到您的应用程序)自定义过滤器:

app.filter("notEqual", function() {
    return function(items, key, value) {
        var filtered = [];
        items.forEach(function(item) {
            if (item && (item[key] !== undefined) 
                    && (item[key] !== value)) {
                filtered.push(item);
            }
        });
        return filtered;
    };
});

然后像这样在任何指令中使用它:

...| notEqual:'<keyName>':<valueToCompareAgainst>

例如:

app.directive("mytag", function() {
    return {
        restrict: "E",
        template: "<div ng-repeat=\"item in myModel | notEqual:'a':null\">"
                + "    item: {{item}}"
                + "</div>",
        scope: {
            myModel: "="
        }
    };
});

另见其他 short demo .


更新

将服务或工厂用于实用方法可能是一个更好的主意,这些实用方法应该对许多 Controller /范围可用并且应该是可定制的。例如:

app.factory("notNullFactory", function() {
    var factory = {};
    factory.notNull = function(caption) {
        return function(item) {
            console.log(caption + " " + JSON.stringify(item));
            return (item !== null);
        };
    };
    return factory;
});

现在,您可以使用 notNullFactorynotNull(...) 函数来创建可自定义的过滤器函数:

app.directive("mytag", function(notNullFactory) {
    return {
        restrict: "E",
        template: "<div>"
                + "    <div ng-repeat=\"item in myModel | filter:notNull('Checking')\">"
                + "        item: {{item}}"
                + "    </div>"
                + "</div>",
        scope: {
            myModel: "="
        },
        link: function($scope) {
            $scope.notNull = function(caption) {
                return notNullFactory.notNull(caption);
            };
        }
    };
});

另请参阅其他 short demo .


不是你的过滤器没有被调用,而是它没有被定义。在定义 $scope.notNull 时,将其设置为等于 $rootScope.notNull,后者未定义

相反,您可以去掉 link 属性并使用:

...| filter:$parent.notNull()...

另请参阅此 short demo .

关于javascript - angular 在过滤器中从 $rootScope 调用实用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19706503/

相关文章:

javascript - 通过 jQuery 中的对象初始值设定项设置数据属性

javascript - Angular 如何过滤大于 ng-click?

javascript - 检测 $last 的指令不适用于 angular.js 中的 ng-if

javascript - 自定义 Angular Directive(指令)未呈现

javascript - HTML5。如何在绘制的 Canvas 组件中添加鼠标事件

javascript - 合并 JSON 并覆盖值

angularjs - 拒绝执行来自 '*' 的脚本,因为它的 MIME 类型 ('application/json' ) 不可执行,并且启用了严格的 MIME 类型检查

css - AngularJS CSS 转换 : List Item with Controls That Slide In/Out

angularjs - 将服务/工厂注入(inject)指令

javascript - 当 "dragging"Chrome 中的图像时,mouseup 事件未触发