Wednesday, 25 January 2017

Create a Fileupload Directive in Angular Js

In this post we are going to see how to create a Fileupload Directive in Angular Js. Using that directive we can able to get files list, success callback, error callback, input user data, url to upload files,method etc.

For this we have to add the two module reference files, from this file we have to add angularFileUpload module to our app module.

angular-file-upload.js
angular-file-upload-shim.js

Add above two files in the project and add script tag in the index.html

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


Result Directive will be like this :

  <fileupload-form asyncurl="~/api/Blog"
                             method="post"
                             input-data="filedata"
                             fileselect-callback="uploadfiles(files)"
                             success-callback="success(data,status,headers,config)"

                             error-callback="error(data,status,headers,config)">
  </fileupload-form>




Directive:

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

 rgapp.directive('fileuploadForm', ['$upload'function ($upload) {
    return {
        scope: {
            asyncurl: '@',
            method: '@',
            successCallback: '&',
            fileselectCallback:'&',
            errorCallback: '&',
            inputData:'='
        },
        restrict: 'E',
        templateUrl:'../App/templates/upload.html',
        link: function (scope, element, attr, cntrl) {

            var uploadingFiles = [];
            var uploadFileHandlers = [];

            scope.uploadedFilesString = '';

            scope.uploading = function(){
                for (var i = 0; i < uploadingFiles.length; i++) {
                    var _file = uploadingFiles[i];

                    (function (indx) {
                        uploadFileHandlers[indx] = $upload.upload({
                            url: attr.asyncurl,
                            method: attr.method,
                            file: _file,
                            data: scope.inputData
                        })
                            .progress(function (prg) {
                                console.log("index " + indx);
                                console.log(prg);
                             })
                            .success(function (data, status, headers, config) {
                                if (scope.successCallback)
                                scope.successCallback({ data: data, 
                                      status: status, 
                                      headers: headers, 
                                      config: config });
                            })
                            .error(function (data, status, headers, config) {
                                if (scope.errorCallback)
                                scope.errorCallback({ data: data, 
                                       status: status, 
                                       headers: headers, 
                                       config: config });
                            });

                   })(i);

                }
            }

            scope.abort = function (indx) {
                uploadFileHandlers[indx].abort();
            }

            scope.uploadedFiles = function (files) {
                uploadingFiles = files;
                scope.uploadedFilesString = '';
                for (var i = 0; i < uploadingFiles.length; i++) {
                    scope.uploadedFilesString += uploadingFiles[i].name + ";";
                }
                if (scope.fileselectCallback)
                    scope.fileselectCallback({ files: files });
            }
           
            scope.browseFiles = function () {
                document.getElementById('rgfile').click();               
            }
           
        }
    }
}]);



Template:

<div>
    <div class="">
        <div class="form-inline" style="padding:20px">
            <label>Files :</label>
            <input type="text" ng-model="uploadedFilesString" class="form-control" />
            <button ng-click="browseFiles()" class="btn btn-sm">Browse</button>
            <button ng-click="uploading()" class="btn btn-sm btn-success">Upload</button>
        </div>
        <div class="form-group">
            <input  type="file" style="display:none" ng-file-select="uploadedFiles($files)"                      class="form-control" id="rgfile"
                    ng-model="user.file" multiple />
        </div>         
    </div>

</div>



Index.html

    <script src="~/Scripts/angular.js" type="text/javascript"></script>
    <script src="~/Scripts/angular-route.js" type="text/javascript"></script>
    <script src="~/Scripts/angular-file-upload.js" type="text/javascript"></script>
    <script src="~/Scripts/angular-file-upload-shim.js" type="text/javascript"></script>

    <script src="~/App/app.js" type="text/javascript"></script>

<div ng-controller="blogcontroller">
    <div>
        <h3>Angular js File Upload</h3>
    </div>
    <div>
        <div class="form-inline">
            <label>Tracking id :</label>
            <input type="text" class="form-control" ng-model="filedata.trackingid" />
        </div>
        <br />
        <div class="form-inline">
            <label>Description :</label>
            <input type="text" class="form-control" ng-model="filedata.description" />
        </div>
        <div style="margin-left:25px;">

            <fileupload-form asyncurl="~/api/Blog"
                             method="post"
                             input-data="filedata"
                             fileselect-callback="uploadfiles(files)"
                             success-callback="success(data,status,headers,config)"
                             error-callback="error(data,status,headers,config)">
           </fileupload-form>

        </div>
    </div> 

</div>



Controller:


rgapp.controller('blogcontroller', ['$scope','$upload',function ($scope,$upload) {

    $scope.Files = [];
    $scope.FilesData = [];
    $scope.filedata = { trackingid:'', description:''};

    $scope.success = function (data,status,headers,config) {
        console.log('config');
        console.log(config);
        $scope.FilesData.push(data);
    }

    $scope.error = function (data,status,headers,config) {
        console.log('error');
        console.log(config);
    }

    $scope.uploadfiles = function (files) {
        console.log(files);
    }

    

}]);




Output:





From this post you can learn how to create a fileupload directive in Angular js

Friday, 4 November 2016

Two way binding in Angular 2

Two way data binding is the concept which makes the Angular in to the Peek position in front end development for versions 1.x, later for version 2 some of the news are reached to the users that Two way data binding is no more in Angular2, but in stable version of Angular2 we have the Two way Data Binding, Now we see the sample of Two way data binding.

The Syntax for Two way Data binding is    [(ngModel)]="propertyName"



<div class="container">
    <br />

        Height : <input type="text" [(ngModel)]="height">
        Background : <input type="text" [(ngModel)]="background">
        Class : <input type="text" [(ngModel)]="classname">
        <button type="submit" [style.height.px]="height" 
                [style.background]="background" 
                [class]="classname"            
                >Submit</button>
    </div>



In the above code you can see in each input control we are binding the value to a model using ngModel, and the model is bind to the button properties.

This alone doesnt make sense to work the ngModel in the Angular2 Applications. we have to add one more thing i.e adding FormsModule in the main module, then only ngModel will work.


import { FormsModule } from '@angular/forms';





    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    import { AppLoadComponent } from './app.load.component'
    import { UserRoutingModule } from './Routing/user.routing.module';
  
    @NgModule({
        imports: [BrowserModule,HttpModule,FormsModule,AppRoutingModule],
        exports: [],
        declarations: [AppLoadComponent],
        providers:[],
        bootstrap:[AppLoadComponent]
    })
    export class AppModule { 

    }






From this post you can learn how to do the Two way Data Binding in the Angular2 Applications.