Solved

Custom Directive using angularjs

Posted on 2014-09-21
8
314 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
 

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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
This article discusses four methods for overlaying images in a container on a web page
In this tutorial viewers will learn how to embed an audio file in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: : The declaration should display (CODE) HTML5 is supported by the most recent versions of all major browsers…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

863 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

Need Help in Real-Time?

Connect with top rated Experts

27 Experts available now in Live!

Get 1:1 Help Now