Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Friday, May 6, 2016

AngularJS - Multiselect Drop down

In some cases, we need to create multi select dropdown. With AngularJS directive it is very easier to implement

Okay, let me first show basic multi select dropdown without any angularJS

<select data-ng-model="model" data-ng-options="value as name for item in itemlist" multiple>
    <option value="" style="color:gray;">-Select Item-</option>
</select>

Here we used simple Select element with multiple attribute. It allows you to select multiple items from dropdown. But drawback is, we should use Ctrl key to select multiple items and also style is not that much easier to customize.


To resolve these dependencies, we can choose AngularJS directive as solution.

app.directive('multiSelectDropDown', function () {
        return {
            restrict: 'AE',
            scope: {
                model: '=',
                options: '=',
                optionsName: '@',
                optionsValue: '@',

            },
            template: "<div class='btn-group dropdown' style='width:100%'>" +
             "<input type='text' value='{{model.toString()}}' data-toggle='dropdown' class='dropdown-toggle' placeholder='Click to select' disabled>" +
             "<button class='btn btn-small dropdown-toggle' 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='glyphicon glyphicon-ok'></i>  Select All</a></li>" +
                         "<li><a data-ng-click='deselectAll();'><i class='glyphicon glyphicon-remove'></i>  Deselect All</a></li>" +
                         "<li class='divider'></li>" +
                         "<li data-ng-repeat='option in options'>" +
                         "<a data-ng-click='setSelectedItem()'><span class=\"{{isChecked(option) ? 'glyphicon glyphicon-ok' : ''}}\"></span>&nbsp;{{option[''+optionsName+'']}}&nbsp;</a>" +
                         "</li>" +
                     "</ul>" +
                 "</div>",
            controller: function ($scope) {

                $scope.selectAll = function () {
                    $scope.model = [];
                    $scope.options.forEach(function (option, index) {
                        $scope.model.push(option[$scope.optionsValue]);
                    });
                };

                $scope.deselectAll = function () {
                    $scope.model = [];
                };

                $scope.setSelectedItem = function () {
                    var selected = this.option;
                    if ($scope.model == undefined || $scope.model == null)
                        model = [];

                    if (_.contains($scope.model, selected[$scope.optionsValue])) {
                        $scope.model = _.without($scope.model, selected[$scope.optionsValue]);
                    } else {
                        $scope.model.push(selected[$scope.optionsValue]);
                    }

                    return $scope.model;
                };

                $scope.isChecked = function (selected) {
                    if ($scope.model == undefined || $scope.model == null)
                        $scope.model = [];

                    if (_.contains($scope.model, selected[$scope.optionsValue])) {
                        return true;
                    }
                    return false;
                };
            }
        }

    });



This directive you can include into your AngularJS application as directive

 var app = angular.module('yourAppName');


In HTML, we can call this directive simply like below

 <multi-select-drop-down model="model" options="itemlist" options-name="name" options-value="value "></multi-select-drop-down>



This requires BootStrap css file, Glyphicons to make work.


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, December 24, 2015

JavaScript - Simple Email without any server code

I have thought of using simple JavaScript Email feature using "mailTo:". But this is not used for bigger body contents or if you planned for much styles.

Use below JavaScript Method to send emails.

You can use more URL encode to format body.

Ref for URL Encode:  http://www.w3schools.com/tags/ref_urlencode.asp
For MailTo Documentation:  http://www.ietf.org/rfc/rfc2368.txt

JavaScript:

function SendEmail() {

   var subject = 'Mail subject goes here..';
   var body = 'Hi,%0D%0A %0D%0A' +
            'Some of your content %0D%0A%0D%0A' +
            'Next line of body goes here.%0D%0A' +
            '%E2%80%A2 Text within Bullet Text here %E2%80%A2 %0D%0A' +
           
            '%0D%0A Thanks &amp; Regards,%0D%0A' +
            'Your signature goes here..';


    window.location = 'mailto:?subject=' + subject + '&body=' + body;

    return false;

};

HTML:

<input type="button" value="Email" onclick="SendEmail();"/>

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, July 20, 2015

JavaScript - Pinch and Zoom using Hammer JS

How to zoom content and not header or footer. Follow as below

Its simple with Hammer JS, download from here http://hammerjs.github.io/  or from Nuget package.

HTML Page:

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
...
<script src="~/Scripts/hammer.min.js"></script>
...
<div id="someContainer">
..Some Content goes here
</div>

<script type="text/javascript">
    $(document).ready(function () {
        //Regisister here
        var element = $('#someContainer');
        contentPinchIntializer(element[0]);
    });

</script>


JavaScript to Pinch and Zoom content:
- Here i created max scale as 5, you can customize it
- Here i added Margin left and Margin Right to avoid space issue while on zooming, you can adjust the pixels however you want
- Added touch-action to enable horizontal scrolling

var contentPinchIntializer = function (element) {
    var scale = 1;
    var currentScale = null;
    var currentMarginLeft = null;
    var currentMarginRight = null;

    var pinchInHanlder = function (e) {
        scale = event.gesture.scale == null ? scale : event.gesture.scale;
        currentScale = currentScale == null ? scale : currentScale;
        currentMarginLeft = currentMarginLeft == null ? $(this).css("margin-left") : currentMarginLeft;
        currentMarginRight = currentMarginRight == null ? $(this).css("margin-right") : currentMarginRight;

        if (scale < currentScale) {
            scale = currentScale + 0.1;
            $(this).css({ "margin-left": currentMarginLeft, "margin-right": currentMarginRight });
        }

        scale = ('scale(' + (scale - 0.1).toString() + ')');

        $(this).css({ 'transform': scale, '-ms-transform': scale, '-webkit-transform': scale });
    };

    var pinchOutHandler = function (e) {
        scale = event.gesture.scale == null ? scale : event.gesture.scale;
        currentScale = currentScale == null ? scale : currentScale;
        currentMarginLeft = currentMarginLeft == null ? $(this).css("margin-left") : currentMarginLeft;
        currentMarginRight = currentMarginRight == null ? $(this).css("margin-right") : currentMarginRight;

        if (scale <= 5) {
            $(this).css({ "margin-left": "200px", "margin-right": "100px" });
            scale = ('scale(' + (scale + 0.1).toString() + ')');
            $(this).css({ 'transform': scale, '-ms-transform': scale, '-webkit-transform': scale });
        }
    };

    var hammertime = Hammer(element).on("pinchin", pinchInHanlder).on("pinchout", pinchOutHandler);

    $(element).css("touch-action", "manipulation");


}