为什么angular返回回调函数内部的函数

Why angular returns a function inside the callback function?

本文关键字:函数 内部 回调 angular 返回 为什么      更新时间:2023-09-26

要定义Angular的过滤器,您应该编写:

angular.module('app', [])
.filter('mix', function () {
    // Why do we return a function here?
    return function (input) {
        var output;
        // doing some business here
        return output;
    };
});

为什么Angular在传递给filter函数的回调函数中返回一个函数?为什么不将其用作过滤器定义的占位符和模板呢?这种语法对开发人员一点也不友好。Angular在使用这个函数嵌套时有什么限制?这是一种模式吗?

我想看起来合乎逻辑和正常的(基于大量使用jQuery和其他库)是这样的语法:

angular.module('app', [])
.filter('mix', function (input) {
    var output;
    // doing some business here
    return output;
});

这一切都与Angular进行依赖注入的方式有关。

您希望能够将服务注入过滤器,但返回一个不使用依赖项注入的函数。

例如,假设您的过滤器使用$location服务:

angular.module('app', [])
.filter('mix', function ($location) {
    // Location got injected.
    // create some private functions here
    function process(input) {
       // do something with the input and $location
    }
    return function (input) {
        return process(input);
    };
});

您也可以从这个例子中看到,通过这种方式可以创建仅对此筛选器可用的"私有"函数。