** Привет, я не могу отформатировать номер телефона с показом в формате pageload, должен быть "123-456-7890", я попробовал другой сценарий, но не получил. может ли кто-нибудь помочь мне в этом.
angular.module("smbApp")
.directive("controlDeviceSummary", function(){
return {
restrict: 'E',
templateUrl: 'templates/device_summary.template',
controller: 'DeviceSummaryCtrl'
}
.directive("formatPhone",function(){
return{
link:function (scope, element, attr){
var phoneforamt= function(value){
var value = value.replace(/(\d{3})(\d{3})(\d{4})/);
}
}
}
})
});
<tbody>
<tr ng-repeat="detail in details track by $index">
<td><a href="#">{{detail.firstName}}, {{detail.lastName}}</a></td>
<td><a href="#" formatPhone >{{detail.mobileNumber}}</a></td>
</tr>
</tbody>
**
https://jsfiddle.net/x443m0ye/
angular
.module('myApp',[])
.controller('phoneCtrl',function($scope){
$scope.data = {
phone:1234567890
}
})
.factory('phoneFormatS',function(){
return function(value){
if(typeof value === 'number'){
value = value + '';
}else if(typeof value !== 'string'){
return value;
}
return value.replace(/(\d{3})(\d{3})(\d{4})/,"$1-$2-$3");
}
})
.directive('phoneFormatD',function(phoneFormatS){
return {
scope:{
number : '=phoneFormatD'
},
link:function(scope,elem,attr){
scope.$watch('number',function(newValue,oldValue){
if(typeof newValue === 'undefined') return
elem.html(phoneFormatS(newValue ));
})
}
}
})
.filter('phoneFormatF',function(phoneFormatS){
return function(number) {
return phoneFormatS(number);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<body ng-app="myApp" ng-controller="phoneCtrl">
<input type="text" ng-model="data.phone">
<br>
<p phone-format-d = "data.phone"> </p>
<p>{{data.phone | phoneFormatF}}</p>
</body>
Вам нужно использовать элемент в функции link
, а затем изменить текст следующим образом:
angular.module("smbApp")
.directive("controlDeviceSummary", function(){
return {
restrict: 'E',
templateUrl: 'templates/device_summary.template',
controller: 'DeviceSummaryCtrl'
})
.directive("formatPhone",function(){
return {
link:function($scope, element, attr){
oldNumber = element.text();
formattedNumber = oldNumber.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3'));
element.text(formattedNumber);
}
}
});
Кроме того, должен быть формат змеиной оболочки вместо camelCasing один в разметке:
<td><a href="#" format-phone>{{detail.mobileNumber}}</a></td>
Попробуй это:
var newVal = /(\d{3})(\d{3})(\d{4})/.exec(value); //returns an array filled with required values. Index 0 contains original value.
newVal.splice(0,1); //remove original value.
newVal.join("-"); //join the values with required separator ('-').
{{ detail.mobileNumber | formatPhone }}
. Вот вопрос относительно этого: stackoverflow.com/questions/12700145/…var value
после вызова replace (). Кажется, нигде не используется.