Solved

Custom Directive using angularjs

Posted on 2014-09-21
8
307 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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Building a website can seem like a daunting task to the uninitiated but it really only requires knowledge of two basic languages: HTML and CSS.
In this tutorial viewers will learn how to embed videos in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <video> tag to insert a video. Define the src as the URL of your video; this is similar to …
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

747 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

14 Experts available now in Live!

Get 1:1 Help Now