Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Custom Directive using angularjs

Posted on 2014-09-21
8
319 Views
Last Modified: 2014-09-22
Hi Experts,

I am looking for some working example on creating custom directive for Telephone no -(123-456-6789) using angularjs .I have following requirements for this

a)When user leaves the Telephone text box and if it matches the pattern then it automatically show as 3 chunks  in the UI.That means if user enters 1234567891 it should display as 123-456-7891.

b)when I retrieve data from api it should also display as 3 chunks in the UI.

Thanks in advance
0
Comment
Question by:ksd123
  • 4
  • 4
8 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 40335406
Hope that help : http://jsfiddle.net/stwwhgxa/

var myApp = angular.module("myApp", []);

var myCtrl = myApp.controller("myCtrl",["$scope", function($scope) {
    $scope.phone1 = "1234567890";
}]);

myApp.directive("phone", function () {
    return {
        restrict: "A",
        link: function (scope, element, attr) {
            var formatPhone = function() {
                var phone1 = scope.phone1;
                phone1 = phone1.replace(/\D/g, "").substr(0,10);
                if(phone1.length>6) {
                    scope.phone1 = phone1.substr(0,3) + "-" + phone1.substr(3,3) + "-" + phone1.substr(6);
                }
                else if(phone1.length>3) {
                    scope.phone1 = phone1.substr(0,3) + "-" + phone1.substr(3);
                }
                scope.$apply();
            }
            element.bind("focus", function () {
                scope.phone1 = scope.phone1.replace(/\D/g, "").substr(0,10);
                scope.$apply();
            });
            element.bind("blur", formatPhone);
        }
    };
});

Open in new window

0
 

Author Comment

by:ksd123
ID: 40335848
Thank you so much for your time.Actually we have seperate folder  for directives and can be consumed by any  module in the application.In the directive at line we are directly referring controller variable like this "scope.phone1", i believe this should be generic.Because this directive can be consumed by "myCtrl1" or "myCtrl2" etc.How can I achieve this?

secondly when i retreive data from API like (1234567890) and should display as 123-456-7890 but here we are formatting the phone no inside directive? How to do this? Please  help me on this

once again thank you for your time
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 40335964
You right, the first code was very bad...
Check here : http://jsfiddle.net/stwwhgxa/9/

var myApp = angular.module("myApp", []);

var myCtrl = myApp.controller("myCtrl",["$scope", function($scope) {
    $scope.phone1 = "1234567890";
}]);

myApp.directive("phone", function ($timeout) {
    return {
        restrict: "A",
        require: "ngModel",
        link: function (scope, element, attr, ngModelCtrl) {
            var formatPhone = function() {
                var phone = element.val();
                phone = phone.replace(/\D/g, "").substr(0,10);
                scope[attr.phone] = phone;
                if(phone.length>6) {
                    element.val( phone.substr(0,3) + "-" + phone.substr(3,3) + "-" + phone.substr(6) );
                }
                else if(phone.length>3) {
                    element.val( phone1.substr(0,3) + "-" + phone1.substr(3) );
                }
                ngModelCtrl.$setViewValue(element.val())
                scope.$apply();
            }
            element.bind("focus", function () {
                element.val( element.val().replace(/\D/g, "").substr(0,10) );
                ngModelCtrl.$setViewValue(element.val());
                scope.$apply();
            });
            element.bind("blur", function() {
                formatPhone();
                scope.$apply();
            });
            $timeout(formatPhone, 1);
        }
    };
});

Open in new window

0
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 

Author Comment

by:ksd123
ID: 40336283
Thanks @leakim971.Can you please fix following issues

1)We are still hard coding field name (phone1) in the directive at  line 20  
"element.val( phone1.substr(0,3) + "-" + phone1.substr(3) );"

Open in new window

.
can we avaoid this?

2)I  should not format the phone no until user enters valid phone no 1234567890->123-456-7890 (ie .Exact 10 digits).
If user enters <10 or >10 digits which is invalid , I should not format and need to show error message.But now it is formatting(displaying as 3 chunks)  even if I enter 9,8 digits.

3)why do we need $timeout ?

Sorry to bother you.I have to write few more directives for SSN,ZIP etc and trying to understand how to write directives

Thank you in advance
0
 
LVL 82

Expert Comment

by:leakim971
ID: 40336368
1) it's a mistake, we should have phone.substr(0,3) + "-" + phone.substr(3)
2)  so use inside the format function :if(phone.length==10) {

update the jsfiddle to let me know you understand the code, thanks
0
 

Author Comment

by:ksd123
ID: 40336567
Thank you so much.Here is the updated fiddle directive and correct me if I am wrong

1)Removed below condition, i don't think we need this

 else if(phone.length>3) {
                    element.val( phone1.substr(0,3) + "-" + phone1.substr(3) );
                }

Open in new window

2)Removed " $timeout(formatPhone, 1);".why do we need $timeout ? it's working fine without this statement.

3) If i enter more than 10 digits,it's removing remaing digits automatically.It should show error messages "Exact 10 Numbers only" or if user enter characters it should show message "Numbers only"  and have added below code and it's not working fine.Can you fix this

 <span class="error" ng-show="myForm.input1.$error.phone">Numbers only!</span>
        <span class="error" ng-show="myForm.input1.$error.phone">Exact 10 Numbers only!</span>

4)why do we need "element.bind ("focus") and ("blur") functions in the directive?

Thank you
0
 
LVL 82

Expert Comment

by:leakim971
ID: 40336601
0) it's wrog, you want to format (so run the whole code) ONLY if you've 10 chars so place you if at the begging

         var formatPhone = function() {
                var phone = element.val();
               if(phone.length==10) {
1) good
2) for the first call of format function (look it not anymore present), it you did not get any error that's fine...
3) if(phone.length==10) {
         // format it
    }
    else if(phone.length>10) {
        // alert / show error
    }
4) remove it and see what happen, please note it's not a filter
0
 

Author Closing Comment

by:ksd123
ID: 40336691
Thank for your explanation. I appreciate your valuable time.
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Logon script fails 23 45
Selecting Right Partition 6 68
.htaccess css/images no longer loading 4 35
troubleshoot a python script 8 16
Use these top 10 tips to master the art of email signature design. Create an email signature design that will easily wow recipients, promote your brand and highlight your professionalism.
Find out what you should include to make the best professional email signature for your organization.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question