2014-02-08 31 views
3

當我是相當新的角度和我可能失去了一些東西很明顯,但我有以下的自定義過濾器:角插值誤差數字格式

propertyApp.filter('telLink', function() { 
return function(tel) { 

    // To avoid interpolating error 
    if(typeof(tel) != undefined) { 

     // Remove any leading zeros 
     if(tel.charAt(0) === '0') { 
      tel = tel.substr(1); 
     } 

     tel = "44" + tel; 

     // Remove any internal whiespace 
     return tel.replace(" ", ""); 
    } 
} 

});

當我使用這個視圖中我得到這個:

Can't interpolate: tel:{{property.agent_phone | telLink}} 
TypeError: Cannot call method 'charAt' of undefined 

有人能指出我在正確的方向?提前致謝。

回答

5

而不是

if(typeof(tel) != undefined) { 

只是做

if (tel) { 

此檢查 「truthyness,」 和一個未定義的電話將無法通過該測試(目前的代碼可以讓通過不定值)

js有很多奇怪的不一致的行爲。這裏是谷歌上的最好鏈接:http://www.sitepoint.com/javascript-truthy-falsy/

+2

更好的方法是使用'angular.isDefined(tel)'。它大體上做同樣的事情,但保證價值適合角度消費。 – Soviut