2013-08-29 137 views
2

要确定一个角的过滤器,你应该写:为什么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; 
    }; 
}); 

为什么角返回传递给filter功能的回调函数内的功能?为什么不使用它作为过滤器定义的占位符和模板? 这个语法根本不是开发者友好的。 Angular有什么限制使它使用这个函数嵌套?这是一种模式吗?

我猜(基于大量使用jQuery和其他库)什么似乎是合乎逻辑和正常是这句法:

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

回答

2

这一切都与角不依赖注入的方式做。

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

例如,让我们说,你的过滤器使用$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); 
    }; 
}); 

您也可以从这个例子看到,做这种方式可以让你创建仅适用于该过滤器的“私人”的职能。

+0

那么,是否可以使用'['$ location',function(){}]'语法,并将该函数用作过滤器,而不是嵌套函数?它与封闭有什么关系? –

+0

是的。如果你想使用数组(minify-safe)语法,它也可以在这里工作。 –

+0

是的,封闭是其中的一部分。我的'process()'函数在返回函数中关闭。您放入更高级别函数的任何其他变量也将被关闭。 –

相关问题