Showing posts with label AngularJS. Show all posts
Showing posts with label AngularJS. Show all posts

Friday, January 8, 2016

AngularJS - Custom form validation

We can have some situation to use custom validations to our input fields, we can use following code to implement it.

Here my case is, I want to validate multiple emails field and have to show field error using AngularJS Form Validation.

For multiple email JavaScript validation check here http://rbalajiprasad.blogspot.in/2015/04/javascript-validate-multiple-email.html 

For AngularJS Form validation check here http://www.w3schools.com/angular/angular_validation.asp


HTML Page:

<p>Email:<br>
  <input type="email" name="email" ng-model="email" required>
  
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
  
<span ng-show="myForm.email.$error.required">Email is required.</span>
  
<span ng-show="myForm.email.$error.validEmail">Invalid email address.</span>
  
</span>
</p>
<p>
  
<input type="button" ng-click="submit()"
  ng-disabled=
"myForm.email.$dirty && myForm.email.$invalid">
</p>


AngularJS Controller

$scope.Submit = function () {
     //your validation
            var isValidEmail = isValidEmailAddress($scope.email.ToAddress);
            $scope.myForm.email.$setValidity("validEmail", isValidEmail);

            var isValid = $scope.myForm.$valid;
            if (!isValid) { return; }

//your logic goes here

        };

Thursday, September 10, 2015

AngularJS - Multiple Select Dropdown with Comma Seperated ngModel

My requirement is to create multiple select dropdown and ngmodel should result with comma seperated value. For that, i have created following directive

      app.directive('multiSelectDropDown', function () {
        return {
            restrict: 'E',
            scope: {
                model: '=',
                options: '='
            },
            template: "<div class='btn-group dropdown' style='width:100%'>" +
             "<input type='text' ng-model='model' style='width:92%;height:36px;float:left;' class='dropdown-toggle' data-toggle='dropdown' placeholder='Click to select' disabled>" +
             "<button class='btn btn-small dropdown-toggle' style='width:8%;height:36px;' data-toggle='dropdown'  ><span class='caret'></span></button>" +
                     "<ul class='dropdown-menu'  style='width:100%'  aria-labelledby='dropdownMenu'>" +
                         "<li><a data-ng-click='selectAll()'><i class='glyphicons ok'></i>  Select All</a></li>" +
                         "<li><a data-ng-click='deselectAll();'><i class='glyphicons remove'></i>  Deselect All</a></li>" +
                         "<li class='divider'></li>" +
                         "<li data-ng-repeat='option in options'>" +
                         "<a data-ng-click='setSelectedItem()'><span data-ng-class='isChecked(option)'></span>&nbsp;{{option}}</a>" +
                         "</li>" +
                     "</ul>" +
                 "</div>",
            controller: function ($scope) {

                $scope.selectAll = function () {
                    $scope.model = _.unique($scope.options).toString();
                };
                $scope.deselectAll = function () {
                    $scope.model = "";
                };

                $scope.setSelectedItem = function () {
                    var selected = this.option;
                    if ($scope.model != undefined && $scope.model != null && _.contains($scope.model.split(','), selected)) {
                        $scope.model = _.without($scope.model.split(','), selected).toString();
                    } else {
                        var arrayModel = [];
                        if ($scope.model != undefined && $scope.model != null && $scope.model != "")
                             arrayModel = $scope.model.split(',');
                        arrayModel.push(selected);
                        $scope.model = arrayModel.toString();;
                    }
                    return false;
                };
                $scope.isChecked = function (selected) {
                    if ($scope.model != undefined && $scope.model != null && $scope.model != "") {
                        if (_.contains($scope.model.split(','), selected)) {
                            return 'glyphicons ok';
                        }
                    }
                    return false;
                };
            }
        }
    });


In module, we can include this directive and just we set in html as follows

//ArrayList = [‘A1’,’A2’,’A3’]
//modelToBind = “A1,A2”


<multi-select-drop-down model="modelToBind" options="ArrayList"></multi-select-drop-down>

Monday, April 20, 2015

JavaScript - Format URL's protocol

Formatting URL with protocol is required when we binding it to anchor tag.

For example below code anchor tag will redirect to relative path because it doesn't have protocol such as Http, Https etc.,

Below code will check protocol exist or not and add in anchor tag

function formatHttp(urlPath) {
    var urlPattern = new RegExp("^(?:f|ht)tps?://");
    if (!urlPattern.test(urlPath)) {
        urlPath = "http://" + urlPath;
    }
    return urlPath;

}



Below example shows in angularJS

HTML:

<a ng-href="{{formatHttp(someurl)}}" href="#" target="_blank"> {{someurl}} </a>

someurl is anything like without protocol "www.google.com" or with protocol "http://www.google.com", "https://www.google.com" etc.,


AngularJS Controller:

$scope.formatHttp = function (url) {
        return formatHttp(url);
};


JS File:

function formatHttp(urlPath) {
    var urlPattern = new RegExp("^(?:f|ht)tps?://");
    if (!urlPattern.test(urlPath)) {
        urlPath = "http://" + urlPath;
    }
    return urlPath;
}

Friday, December 19, 2014

AngularJS - Apply Style to currency and percentage texts before bind to UI

I have a scenario where i need to highlight currency amount values and percentage values within html text. I went over so many sites to achieve this and finally got achieved this using AngularJS with JavaScript.

What i expected is below:



What Steps i done to achive this below:

1: Create Javascript function to replace currency and percentage matched text to our required style. In this case i have used regular expression

var ReplaceCurrencyText = function (text) {
    var returnText = text.replace(/(\$?(?=\(.*\)|[^()]*$)\(?(\d{1,6}|\d{1,3},\d{3})(\.\d\d?)?\)?\%?)/g, "<span style=’color:green;’>$1</span>");
    return returnText;
};


Here $1 represents RegEx matched 1st group. Each brackets considered as one group, but in this case i used only one group (i.e., (\$?(?=\(.*\)|[^()]*$)\(?(\d{1,6}|\d{1,3},\d{3})(\.\d\d?)?\)?\%?) ).

2: Create angular directive which used to replace currency and percentage text as required

angularApp.directive('displayStyledCurrencyValue', ['$sce', function ($sce) {

    return {
        restrict: 'AE',
        replace: true,
        template:
                   '<div ng-bind-html="getStyledHtml(htmlText)"></div>',
        scope: {
            htmlText: '='
        },
        link: function (scope, element, attrs) {
            scope.getStyledHtml = function (html) {
                return $sce.trustAsHtml(ReplaceCurrencyText(html));
            };
        }
    };
}]);

Here i have used ng-bind-html to render text as html so that html element will not be shown as text and for this i used $sce.trustAsHtml method to return as html string. JavaScript function ReplaceCurrencyText called inside angular directive to get my required format of currency amount and percentage text.


3: Call this angular directive in html page wherever required and th

<display-styled-currency-value html-text="someValueToBind"></display-styled-currency-value>

Friday, December 5, 2014

AngularJS - Intercept all ajax calls globally

Add following code in app module config section to handle success or error globally.

In below example i have handled 401 unauthorized error globally.

App.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded"; //Post
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
    var interceptor = ['$rootScope', '$q', function (scope, $q) {
        function success(response) {
            return response;
        }
        function error(response) {
            var status = response.status;
            console.log("site error: " + status);
            if (status == 401) {
                window.location.href = currentDomain;
                return;
            }
            // otherwise
            return $q.reject(response);
        }
        return function (promise) {
            return promise.then(success, error);
        }
    }];
    $httpProvider.responseInterceptors.push(interceptor);

}]);