2016-12-15 154 views
0

請幫助修復腳本。如何只允許數字?

HTML:

<input type="text" ng-model="phone" id="phoneInput" ng-change="apt.changePhoneInput(phone)"> 

JS:

var app = angular.module('app', []); 
app.controller('Appctrl', Appctrl, '$scope'); 
function Appctrl($scope){ 
    this.changePhoneInput = function(phone) { 
    var result = phone; 
    console.log('phone', phone); 
    result.replace(/[^+0-9\(\)]/gim,''); 
    console.log('result', result); 
    $scope.phone = result; 
    }; 
} 

JSFIDDLE

我希望允許只輸入數字和後續的符號: '+', '(', ')' ,' - '。但進入之後的任何符號代替不起作用

+0

HTML5 ? 'input type =「number」...>' – fnostro

+0

需要轉義'+'和'-'。你可以使用'\ d'而不是'0-9'。 –

+0

想起來,你可以用'' – fnostro

回答

8

你缺少分配到result變量,替換字符後節選數

result=result.replace(/[^+0-9\(\)-]/gim,''); 

更改後,您是控制器應該像使用

var app = angular.module('app', []); 
app.controller('Appctrl', Appctrl, '$scope'); 
function Appctrl($scope){ 
    this.changePhoneInput = function(phone) { 
    var result = phone; 
    console.log('phone', phone); 
    result=result.replace(/[^+0-9\(\)-]/gim,''); 
    console.log('result', result); 
    $scope.phone = result; 
    }; 
}