2016-09-13 152 views
1

我試圖在AngularJS中編寫自定義過濾器。此過濾器將大寫文本。上執行的代碼,這個錯誤已經拋出 「錯誤:value.split不是一個函數錯誤:value.split不是函數

文件 「filter.js」:

"use strict"; 
    angular.module("MyApp", []); 
    angular.module("MyApp").controller("UserController", ["$scope", function($scope) 
    { 
     this.infos = 
     { 
      firstname: "David", 
      lastname: "Michel", 
      cellphone: 123456 
     }; 
    }]); 

    angular.module('MyApp').filter('capitalize', function() 
    { 
     return function(value){ 
      var result = null; 
      var words = value.split(' '); 
      words.forEach(function(item){ 
       if (result){ 
        result += ' '; 
       }else{ 
        result = ''; 
       } 
       result += item.substr(0, 1).toUpperCase() + item.substr(1).toLowerCase(); 
      }); 
      return result; 
     }; 
    }); 

文件 「filter.html」:

<html ng-app="MyApp"> 

    <head> 
     <script type="text/javascript" src="angular.js"></script> 
     <script type="text/javascript" src="filter.js"></script> 
    </head> 

    <body> 
     <div ng-controller="UserController as user">   
      Firstname : {{user.infos.firstname | capitalize }} 
      Lastname : {{user.infos.lastname | capitalize }} 
      Cellphone : {{user.infos.cellphone | capitalize }}  
     </div> 
    </body> 

</html> 
+0

我們可以看一下你是如何實現在HTML過濾器? –

+0

@NathanBeck我剛剛更新了我的問題:文件「filter.html」 –

+0

@NathanBeck,它的作品var words = value.toString()。split(''); –

回答

0

這個問題似乎是你有一個名爲value的函數參數,它隱藏了外部變量value

試圖聲明自己的價值作爲像這樣的變量:

angular.module('MyApp').filter('capitalize', function() 
{ 
    return function(){ 
     var value = 'something'; 
     var result = null; 
     var words = value.split(' '); 
     words.forEach(function(item){ 
      if (result){ 
       result += ' '; 
      }else{ 
       result = ''; 
      } 
      result += item.substr(0, 1).toUpperCase() + item.substr(1).toLowerCase(); 
     }); 
     return result; 
    }; 
+0

'return function(value)'中的參數'value'是字符串角度切換到過濾器。將它設置爲一個靜態值(在你的例子中,'something')會打敗過濾器的目的,因爲你總是會返回大寫的單詞'Something'。 –