Showing posts with label angular js. Show all posts
Showing posts with label angular js. Show all posts

Monday, 22 April 2019

Create a Drawing Board using Html5 Canvas and draw using mouse

In this post we are going to see  how to create a drawing board using Html5 Canvas and angular.This sample will make users to draw a free flow diagram while just drag the mouse over canvas.

Html
*****
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="style.css">
    <script src="angular.js"></script>
    <script src="app.js"></script>
</head>
<body>

    <div style="margin-left: 400px;">
        <h1>Drawing board, click and drag to draw</h1>
        <canvas width="500" height="500" id="drawingarea" free-flow-drawing></canvas>
    </div>
</body>
</html>

style.css
*********
#drawingarea{
    border-bottom: 1px solid rgba(0,0,0,0.3);    background-color: #FFF;    box-shadow: 0 9px 20px -5px rgba(0,0,0,0.8);}

JS
***
Below directive will draw the canvas container when ever user click and draw above container

var app = angular.module("app",[]);
app.directive('freeFlowDrawing',[function () {
return {
    restrict:'A',    link:function(scope,element,attr){
        var Drawingctx = element[0].getContext('2d');        var oldX;        var oldY;        var drawing = false;                function Draw(ox, oy, nx, ny) {
            Drawingctx.moveTo(ox,oy);            Drawingctx.lineTo(nx,ny);            Drawingctx.lineWidth = 8;            Drawingctx.strokeStyle = "blue";            Drawingctx.stroke();        }
        
        element.bind('mousedown',function (event) {
            oldX = event.offsetX;            oldY = event.offsetY;            Drawingctx.beginPath();            drawing = true;        });
        element.bind('mousemove',function (event) {
            if(drawing) {
                var newX = event.offsetX;                var newY = event.offsetY;                Draw(oldX,oldY,newX,newY);                oldX = newX;                oldY = newY;            }
        });
        element.bind('mouseup',function (event) {
            drawing = false;        });
    }
}
}]);

Output:
******






From this post you can learn how to create a drawing board using canvas and draw using mouse.

Sunday, 29 July 2018

upload a file in AngularJS and also for upload the same file twice

In this post we are going to see how to upload the file to a endpoint and also for upload the same file twice.

Normally what will happen if we upload the same file twice, it wont reflect the changes in the file input control, for that to reflect we have to reset the value to null of that element

Create a View:
we are creating a view which consists of one file upload control, and we are referring the two scripts one is angular js, another one is app.js

<!DOCTYPE html>
<html>
<head>
<title>File upload</title>
<script src="./angular.js"></script>
    <script src="app.js"></script>
</head>

<body >
<div ng-app="myApp">
    <div ng-controller="mainController">
        Browse File <input file-model="file" type="file">
    </div>
</div>
</body>

</html>

we are creating a angular module

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


Create a Controller:
we are creating a controller which consists of following dependencies one is $scope and another one is httpService. we are calling a submit function whenever file is selected. if the upload is success or failure we are resetting the input file value to null. i.e resetting the value


app.
controller('mainController', ['$scope','httpService',function($scope, httpService){

    $scope.
title = 'Sample File upload';

   
$scope.submit = function(){

        httpService.
uploadFile($scope.file).then(function(data){
           
/* This event will reset the file, so same file can be upload again */
           
$scope.$broadcast('resetfile');
       
},function (error) {
            $scope.
$broadcast('resetfile');
       
});

   
};

   
$scope.$watch('file', function (newFile, oldFile) {
       
if(newFile!=undefined) {
            $scope.
submit();
           
console.log('file changed',newFile);
       
}
    })
;

}]);



Create a Directive:
we are creating a directive which will set the modal value, whenever there is a change in the fileupload control, i.e whenever you select a file, we will parse the attrs.fileModel and assign the value to that model on change.

app.directive('fileModel',function ($parse) {

return {

    restrict:'A',
    link: function(scope, element, attrs) {

        var modal = $parse(attrs.fileModel);
        var modalSetter = modal.assign;

        element.bind('change',function () {
            scope.$apply(function () {
                modalSetter(scope, element[0].files[0]);
            })
        });

        scope.$on('resetfile',function (event) {
            element.val(null);
        });

    }

}

});



Create a Service:


app.service('httpService',function ($http) {

    this.uploadFile = function (file) {

        var fileFormData = new FormData();
        fileFormData.append('file', file);

        return $http.post('https://www.sampleservice.com/upload', fileFormData, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        });

    }

});



Output:
*********






If you see the above console, logging of same file twice in upload is reflected by code

From this post we can learn how to upload a file in Angular js and also for upload the same file twice

Friday, 26 January 2018

Create a Drawing Board using Html5 Canvas , Angular and draw using mouse

In this post we are going to see  how to create a drawing board using Html5 Canvas and angular.This sample will make users to draw a free flow diagram while just drag the mouse over canvas.

Html
*****
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="style.css">
    <script src="angular.js"></script>
    <script src="app.js"></script>
</head>
<body>

    <div style="margin-left: 400px;">
        <h1>Drawing board, click and drag to draw</h1>
        <canvas width="500" height="500" id="drawingarea" free-flow-drawing></canvas>
    </div>
</body>
</html>

style.css
*********
#drawingarea{
    border-bottom: 1px solid rgba(0,0,0,0.3);    background-color: #FFF;    box-shadow: 0 9px 20px -5px rgba(0,0,0,0.8);}

JS
***
Below directive will draw the canvas container when ever user click and draw above container

var app = angular.module("app",[]);
app.directive('freeFlowDrawing',[function () {
return {
    restrict:'A',    link:function(scope,element,attr){
        var Drawingctx = element[0].getContext('2d');        var oldX;        var oldY;        var drawing = false;                function Draw(ox, oy, nx, ny) {
            Drawingctx.moveTo(ox,oy);            Drawingctx.lineTo(nx,ny);            Drawingctx.lineWidth = 8;            Drawingctx.strokeStyle = "blue";            Drawingctx.stroke();        }
        
        element.bind('mousedown',function (event) {
            oldX = event.offsetX;            oldY = event.offsetY;            Drawingctx.beginPath();            drawing = true;        });
        element.bind('mousemove',function (event) {
            if(drawing) {
                var newX = event.offsetX;                var newY = event.offsetY;                Draw(oldX,oldY,newX,newY);                oldX = newX;                oldY = newY;            }
        });
        element.bind('mouseup',function (event) {
            drawing = false;        });
    }
}
}]);

Output:
******






From this post you can learn how to create a drawing board using canvas and draw using mouse.

Sunday, 21 January 2018

How to find that service is registered in angular js

In this post we are going to see how to find whether service is register in angular js. for that first we create the service and then inject that as a interceptor.

Define the RequestTracker which will have a common structure to inject a call, four common methods that we can inject for a $http service is response, request, requestError, responseError

var mainApp = angular.module('mainApp', []);

mainApp.factory('RequestTracker'function () {

    var _interceptors = {

        request: function (config) { },
        response: function (response) { },
        requestError: function (requestReject) { },
        responseError: function (response) { }

    };

    return _interceptors;

});


Add the interceptors to the $httpProvider, Here we are adding the RequestTracker to the interceptor.

mainApp.config(['$httpProvider'function ($httpProvider) {

var $injector = angular.injector();
    if(!$injector.has('RequestTracker'))
    $httpProvider.interceptors.push('RequestTracker');

}]);



From this post we can learn how to find the service is registered in Angular JS

Sunday, 30 April 2017

Add authentication token in every http request call in angular js applications

In this post we are going to see how to pass the authentication token in every http request call in angular js application

authService:
*************
 mvcapp.service('authService', ['$localStorage', '$rootScope',function ($localStorage,$rootScope) {

    this.getAuthCode = function () {
        return $localStorage.authuser;
    }

    this.setAuthCode = function (authdata) {
        $localStorage.authuser = authdata;
    }

    this.removeAuthCode = function () {
        delete $localStorage.authuser;       
        var loggeduser = { Status: '', Username: '', Authcode: '' };
        $rootScope.$broadcast('loguser', loggeduser);
    }

    this.isLoggedIn = function () {
        return $localStorage.authuser != null && $localStorage.authuser.Authcode != null;
    }


}]);




Factory:
*********
mvcapp.factory('httpRequest', ['$q', 'authService', function ($q, authService) {

    var _interceptors = {
        request: function (config) {
            if (angular.isObject(config)) {
                config.delay = new Date().getTime();
                var loggedin = authService.getAuthCode();

                if (loggedin!=undefined && loggedin.Authcode != null)
                    config.headers["Authorization"] = "Bearer " + loggedin.Authcode;

            }
            return config;
        },
        response: function (response) {
            if (angular.isObject(response.config)) {
                response.config.delay = new Date().getTime() - response.config.delay;
            }
            return response;
        },
        requestError: function (config) {
            if (angular.isObject(config)) {
                config.delay = new Date().getTime();
            }
            return $q.reject(config);
        },
        responseError: function (response) {
            if (angular.isObject(response.config)) {
                response.config.delay = new Date().getTime() - response.config.delay;
            }
            return $q.reject(response);
        }
    };

    return _interceptors;

}]);



mvcapp.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('httpRequest');
}]);



From this post you can learn how to pass the authentication token in every http request call.

How to write a login authentication using stateprovider and authentication for each state in angular js application

In this post we are going to see how to create the login authentication in angular js application in state provider.

First we have to create the states, Then we have to create the variable name authenticate to the states which ever need the authentication

We are creating a hook for $stateChangeStart event , so when ever we change state this will hooked, from there we are checking whether authenticate is required for this state, if it is required then we are invoking the authService for checking the authentication, if failed then we change the state or transition the state to login state.

var mvcapp = angular.module('mvcapp', ['ui.router', 'ngCookies', 'ngStorage',]);


configure states:

******************

mvcapp.config(['$stateProvider', '$urlRouterProvider', '$localStorageProvider',            
               '$locationProvider',
function ($stateProvider, $urlRouterProvider, $localStorageProvider, $locationProvider) {


    $stateProvider.state('home',
        {
            name: 'home',
            url: '/home',
            templateUrl: 'app/templates/home.html',
            controller: 'homeController'
        })
        .state('about',
        {
            name: 'about',
            url: '/about',
            templateUrl: 'app/templates/about.html',
            controller: 'aboutController'
        })
        .state('login',
        {
            name: 'login',
            url: '/login',
            templateUrl: 'app/templates/login.html',
            controller: 'loginController',
            resolve: { signIn: AlreadySignin }
        })
        .state('register',
        {
            name: 'register',
            url: '/register',
            templateUrl: 'app/templates/register.html',
            controller: 'registerController',
            resolve: { signIn: AlreadySignin }
        })
        .state('profile',
        {
            name: 'profile',
            url: '/profile',
            templateUrl: 'app/templates/profile.html',
            controller: 'profileController',
            authenticate: true
        })
        .state('history',
        {
            name: 'history',
            url: '/history',
            templateUrl: 'app/templates/history.html',
            controller: 'historyController',
            authenticate: true
        })       
        .state("default",
        {
            name: 'default',
            url: '/',
            templateUrl: 'app/templates/home.html',
            controller: 'homeController'
        });
        
    $urlRouterProvider.otherwise('/'); 
    $localStorageProvider.setKeyPrefix('mvcapp');
    $locationProvider.html5Mode(false);

}]);



handling exception in global:

********************************
mvcapp.config(['$provide',function ($provide) {
    $provide.decorator('$exceptionHandler', ['$delegate', '$log'
     function ($delegate, $log) {
        return function (exception, cause) {
            $delegate(exception, cause);
            $log.info(exception.message + " (because of " + cause + " )");
        };
    }])
}]);



check for login, if logged in redirect to home:
***************************************************
AlreadySignin.$inject = ['$rootScope','$state', '$location', 'authService'];

function AlreadySignin($rootScope, $state,$location, authService) {
    if (authService.isLoggedIn()) {      
        return $location.path("/home");      
    }

}



Then we have to write logic in statechangestart event in run based on authenticate variable, now we will see what is the authservice, and what logic it resides


mvcapp.run(['$rootScope', '$location', '$http', 'authService', '$state', '$timeout',
  function ($rootScope, $location, $http, authService, $state, $timeout) {

    if (authService.isLoggedIn())
    {
        $http.defaults.headers.common['Authorization'] = 'Bearer ' +
authService.getAuthCode().Authcode;
    }


    function safeApply(scope, fn) {
        (scope.$$phase || scope.$root.$$phase) ? fn() : scope.$apply(fn);
    }


    $rootScope.$on('$stateChangeStart', function (event, toState, toParams,
fromState, fromParams) {

        if (toState.authenticate && !authService.isLoggedIn()) {
            // User isn’t authenticated
            $state.transitionTo("login");           
            $rootScope.redirect = toState.name;
            event.preventDefault();
        }

        if (toState.authenticate && authService.isLoggedIn()) {
            var role = authService.getAuthCode().Role;
           
        }

        safeApply($rootScope, function () {
            $timeout(function () {
                $rootScope.$broadcast('updatelogin');
            })          
        });

       

    });


}]);





authService:
*************


mvcapp.service('authService', ['$localStorage', '$rootScope',

function ($localStorage,$rootScope) {

    this.getAuthCode = function () {
        return $localStorage.authuser;
    }

    this.setAuthCode = function (authdata) {
        $localStorage.authuser = authdata;
    }

    this.removeAuthCode = function () {
        delete $localStorage.authuser;       
        var loggeduser = { Status: '', Username: '', Authcode: '' };
        $rootScope.$broadcast('loguser', loggeduser);
    }

    this.isLoggedIn = function () {
        return $localStorage.authuser != null && $localStorage.authuser.Authcode != null;
    }



}]);


Output:
*************





















From this post you can learn how to add the authentication for each state in the angular js applications