2014-02-22 81 views
0

我正在通過tutorial創建角度過濾器。我對一些實現感到困惑,它涉及到基本的JavaScript。這裏是鱈魚片段:自定義過濾器語法

// on the app object, the method filter is called passing a name parameter and the function 
myApp.filter('reverse', function() { 
    return function (text) { 
// now a function that accepts text as a parameter is returned  
return text.split("").reverse().join(""); 
// the text parameter splits, revers, and joins the text parameter. 
    } 
}); 

我的問題是爲什麼不能寫這樣的東西呢?在第二行的第一個片段中返回函數的目的是什麼?

myApp.filter('reverse', function (text) { 
    return text.split("").reverse().join(""); 
}); 
+0

因爲你傳給'filter'的函數是依賴注入。 – elclanrs

回答

1

您傳遞給filter的函數是依賴注射。想象一下,你注入的幾件事情:

myApp.filter('uc', function($http, myService, text) { 
    return text.toUpperCase(); 
}); 

myApp.filter('repeat', function($http, $location, myService2, text) { 
    return text + text; 
}); 

你怎麼知道text是在參數列表?現在這些過濾器不構成,因爲參數不匹配。如果你返回的函數總是把值作爲第一個參數,那麼一切都很好,你可以這樣做:

repeat(uc(value))