Saturday 26 December 2015

Upload image from camera to firebase in ionic

Hello,

Here i am introducing a way, by which an user can click a picture by camera and can upload it on the firebase, with login and register functionality.When an user is login and take a picture. This data will be saved on the firebase beck-end services.And when that user again login , can see his picture.

So,
Let's start with the ionic blank app-

ionic start myapp blank
cd my app
ionic platform add android


Now we will include cordova.js library in it.

bower install ngCordova


Then include following line of code before cordova.js in index.html file-

<script src="lib/ngCordova/dist/ng-cordova.js"></script>

in app.js file include the following dependencies-

var myapp = angular.module('myApp', ['ngCordova'])


Then include the following library-


  • The latest Firebase JavaScript library
  • The latest AngularFire AngularJS library


  • Now your index.html file look like-


    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
        <title></title>
        <link href="lib/ionic/css/ionic.css" rel="stylesheet">
        <link href="css/style.css" rel="stylesheet">
        <script src="lib/ionic/js/ionic.bundle.js"></script>
        <script src="js/ng-cordova.min.js"></script>
        <script src="cordova.js"></script>
        <script src="js/firebase.js"></script>
        <script src="js/angularfire.min.js"></script>
        <script src="js/app.js"></script>
    </head>
    
    
    
    
    Now, we will include the camera plugin-
    
    
    cordova plugin add org.apache.cordova.camera
    
    
    
    

    Getting Firebase Started-

    We're not quite ready to talk about Firebase, but we are at a point where it would be a good idea to initialize it. At the top of your www/js/app.js file, outside any AngularJS code, you want to add the following line:
    var fb = new Firebase("https://INSTANCE_ID_HERE.firebaseio.com/");
    
    
    
    
    Of course you need to replace INSTANCE_ID_HERE with 
    your personal Firebase instance. By setting it globally, it will load 
    before AngularJS and can be used throughout your application.
    
    
    We also need to add firebase to our AngularJS module. In the end it will look something like this:
    
    
    
    
    
    
    var myapp = angular.module("starter", ["ionic", "ngCordova", "firebase"]);
    
    
    
    
    
    
    In your login.html file add following lines of code-
    
    
    
    
    <ion-view title="Firebase Login">
        <ion-content>
            <div>
                <div class="list list-inset">
                    <label class="item item-input">
                        <input ng-model="username" type="text" placeholder="Username" />
                    </label>
                    <label class="item item-input">
                        <input ng-model="password" type="password" placeholder="Password" />
                    </label>
                </div>
                <div class="padding-left padding-right">
                    <div class="button-bar">
                        <a class="button" ng-click="login(username, password)">Login</a>
                        <a class="button" ng-click="register(username, password)">Register</a>
                    </div>
                </div>
            </div>
        </ion-content>
    </ion-view>
    
    
    
    
    And in loginCtrl.js file-
    
    
    
    
    
    
    
    
    
    
    myapp.controller("loginCtrl", function($scope, $state, $firebaseAuth) {
    
        var fbAuth = $firebaseAuth(fb);
    
        $scope.login = function(username, password) {
            fbAuth.$authWithPassword({
                email: username,
                password: password
            }).then(function(authData) {
                $state.go("image");
            }).catch(function(error) {
                alert(error);
                console.error("ERROR: " + error);
            });
        }
    
        $scope.register = function(username, password) {
            fbAuth.$createUser({email: username, password: password}).then(function(userData) {
                return fbAuth.$authWithPassword({
                    email: username,
                    password: password
                });
            }).then(function(authData) {
                $state.go("image");
            }).catch(function(error) {
                console.error("ERROR: " + error);
                alert(error);
            });
        }
    
    });
    
    
    
    
    And in image.html file-
    
    
    
    
    
    
    <ion-view title="My Images" ng-init="">
        <ion-nav-buttons side="right">
            <button class="button button-icon icon ion-camera" ng-click="upload()"></button>
        </ion-nav-buttons>
        <ion-content>
            <div class="row" ng-repeat="image in images" ng-if="$index % 4 === 0">
                <div class="col col-25" ng-if="$index < images.length">
                    <img ng-src="data:image/jpeg;base64,{{images[$index].image}}" width="100%" />
                </div>
                <div class="col col-25" ng-if="$index + 1 < images.length">
                    <img ng-src="data:image/jpeg;base64,{{images[$index + 1].image}}" width="100%" />
                </div>
                <div class="col col-25" ng-if="$index + 2 < images.length">
                    <img ng-src="data:image/jpeg;base64,{{images[$index + 2].image}}" width="100%" />
                </div>
                <div class="col col-25" ng-if="$index + 3 < images.length">
                    <img ng-src="data:image/jpeg;base64,{{images[$index + 3].image}}" width="100%" />
                </div>
            </div>
        </ion-content>
    </ion-view>
    
    
    In imageCtrl.js file-
    
    
    
    
    
    
    myapp.controller("imageCtrl", function($scope,$state, $ionicHistory, $firebaseArray, $cordovaCamera) {
    
        $ionicHistory.clearHistory();
    
        $scope.images = [];
    
        var fbAuth = fb.getAuth();
        if(fbAuth) {
            var userReference = fb.child("users/" + fbAuth.uid);
            var syncArray = $firebaseArray(userReference.child("imageuploadapp"));
            $scope.images = syncArray;
        } else {
            $state.go("login");
        }
    
        $scope.upload = function() {
            var options = {
                quality : 75,
                destinationType : Camera.DestinationType.DATA_URL,
                sourceType : Camera.PictureSourceType.CAMERA,
                allowEdit : true,
                encodingType: Camera.EncodingType.JPEG,
                popoverOptions: CameraPopoverOptions,
                targetWidth: 500,
                targetHeight: 500,
                saveToPhotoAlbum: false
            };
            $cordovaCamera.getPicture(options).then(function(imageData) {
                syncArray.$add({image: imageData}).then(function() {
                    alert("Image has been uploaded");
                });
            }, function(error) {
                console.error(error);
            });
        }
    
    });
    
    Now your app.js file look like-
    var myapp = angular.module('starter', ['ionic','ngCordova','firebase']) var fb = new Firebase("https://INSTANCE_ID_HERE.firebaseio.com/"); myapp.run(function($ionicPlatform) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if(window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if(window.StatusBar) { StatusBar.styleDefault(); } }); }) myapp.config(function ($stateProvider,$urlRouterProvider) { $stateProvider .state('login', { url: '/login', templateUrl: 'templates/login.html', controller: 'loginCtrl' }) .state('image', { url: '/image', templateUrl: 'templates/image.html', controller: 'imageCtrl' }); $urlRouterProvider.otherwise('/login'); });
    
    
    In firebase, we will add the following rule in Security & Rules section-
    
    
    {
        "rules": {
            "users": {
                ".write": true,
                "$uid": {
                    ".read": "auth != null && auth.uid == $uid"
                }
            }
        }
    }
    
    
    And include the following JSON in data section-
    
    
    {
        "imageuploadapp": {
            "unique_image_id_here": {
                "image": ""
            }
        }
    }
    
    
    
    
    Thanks...
    
    
    
    
    
    
    
    

    Friday 25 December 2015

    Focus event in angularjs

    Hi,

    ngFocus-

                     As the focus event is executed synchronously when calling input.focus() AngularJS executes the expression using scope.$evalAsync if the event is fired during an $apply to ensure a consistent state.

    Here, is an example in which if an user focus on an input box an message will be show down of that input box.

    So, following lines of code, we will add in the style.css file.

    .focus { border-left: 5px solid green !important; background-color: lightgreen; }
    
    
    In home.html file we will add following lines of code-
    
    
    <ion-view><ion-content>
    <div class="container"> <div ng-init="Array = ['List 1','List 2','List 3']"> <h3>Example of Ng-Focus</h3> <div ng-repeat="array in Array"> <input type="text" class="form-control" ng-model="array" autofocus ng-class="{true:'focus',false:'blur'}[isFocused]" ng-focus="isFocused=true" ng-blur="isFocused=false"> <span ng-show="isFocused"><b>{{array}}</b></span> <br /> </div> </div> </div></ion-content></ion-view>


    Thanks....

    Blur event in angularjs

    Hi,

    ngBlur-

                  ngBlur is a directive in ng module.

    It have a special behavior on blur event. A blur event is fired when an element lost his focus.

    As the blur event is executed synchronously also during DOM manipulations (e.g. removing a focused input), AngularJS executes the expression using scope.$evalAsync if the event is fired during an $apply to ensure a consistent state.

     Here i am introducing an example, in which after clicking the input box a text 'ngBlur used' append after the 'Hello welcome to angularjs'.

    So, in home.html file add the following lines of code-

    <ion-view>
    <ion-content>
    <div>
    <h3>Example of Ng-Blur</h3>  <input ng-model="msg" class="form-control" type="text" ng-class="{ myFocus: focus, myBlur: blur }" ng-focus="focus=true;blur=false;" ng-blur="ngBlur()" /> <p>{{msg}}</p>
    </div></ion-content>
    </ion-view>


    In HomeCtrl.js file add the following lines of code-

    Demo.controller('HomeCtrl', ['$scope', '$timeout', function ($scope, $timeout) { $scope.msg = "Hello welcome to angularjs"; $scope.ngBlur = function () { $scope.clicked = false; $timeout(function () { if ($scope.clicked) { return; } $scope.blur = true; $scope.focus = false; $scope.msg = $scope.msg + ' ngBlur used '; }) } }]);
    
    
    
    
    In style.css file add following lines of code-
    
    

    .myBlur { background-color: lightskyblue; } .myFocus { border-left: 5px solid; }
    
    
    
    
    Thanks...

    Monday 14 December 2015

    Currency Converter in Ionic

    Hello,

    Here is a way by which, we can use currency converter in Hybrid application.

    So, now we will start with a blank app.

    ionic start MyConverterApp blank
    cd MyConverterApp

    So, for using the currency converter, here we need to include money.js in our index.html file.
    You can include it from money.js a small javascript library for currency conversion, maintained by Open Exchange Rates.

    Now, we will include following lines of in our index.html file-

    <!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">    <title></title>
        <link href="lib/ionic/css/ionic.css" rel="stylesheet">    <link href="css/style.css" rel="stylesheet">
        <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above    <link href="css/ionic.app.css" rel="stylesheet">    -->
        <!-- ionic/angularjs js -->    <script src="lib/ionic/js/ionic.bundle.js"></script>
        <!-- cordova script (this will be a 404 during development) -->    <script src="cordova.js"></script>
        <script src="js/money.js"></script>    <!-- your app's js -->    <script src="js/app.js"></script>  </head>  <body ng-app="starter" ng-controller="realexchangeCtrl">
      <ion-pane>      <ion-header-bar class="bar-stable bar-calm">          <h1 class="title">Real Exchange Rate</h1>      </ion-header-bar>      <ion-content >          <ion-refresher                  pulling-text="Pull to refresh..."                  on-refresh="doRefresh()">          </ion-refresher>          <div class="list">              <label class="item item-input item-select">                  <div class="input-label">                      From Currency                  </div>                  <select ng-model="Data.fromCurrency" ng-change="getExchangeRate()">                                <option value="">Select</option>                      <option ng-repeat="(key,value)  in result.rates" value="{{key}}">{{key}}</option>                  </select>              </label>          </div>          <div class="list">
                  <label class="item item-input item-select">                  <div class="input-label">                      To Currency                  </div>                  <select ng-model="Data.toCurrency" ng-change="getExchangeRate()">                                 <option value="">Select</option>                      <option ng-repeat="(key,value) in result.rates" value="{{key}}">{{key}}</option>                  </select>              </label>
              </div>
              <div class="list">              <label class="item item-input">                  <div class="input-label">                      Amount                  </div>                  <input id="amount" type="number" placeholder="Amount" ng-model="Data.amount" ng-change="getExchangeRate()">              </label>          </div>          <label class="item item-input">              <span class="input-label">Date</span>              <input id="rateDate" type="date" ng-model="Data.date" ng-change="getExchangeRate()">          </label>          <div class="card" ng-show="exchangeRate">              <div class="item item-text-wrap" style="text-align:center;">                  <h1>{{Data.amount}} {{Data.fromCurrency}} = {{exchangeRate}} {{Data.toCurrency}}</h1>              </div>          </div>      </ion-content>  </ion-pane>  </body></html>


    Now, we will include following lines of code in app.js file-


    .controller('realexchangeCtrl',function($scope,$filter,$ionicLoading,$http,$ionicPopup){        $scope.Data={};        $scope.Data.amount=1;        $scope.Data.currentDate=$filter("date")(Date.now(),'yyyy-MM-dd');        $scope.Data.date=$scope.Data.currentDate;
            var apiKey="your api key";        var baseUrl="http://openexchangerates.org/api/";
            $scope.url=baseUrl+"latest.json?app_id="+apiKey;                $ionicLoading.show();        $http.get($scope.url)            .success(function(response){                $scope.result=response;                            })            .error(function(response,status){                $scope.showAlert('Error!!!',response.message);            })            .finally(function(){                $ionicLoading.hide();            });
            $scope.getExchangeRate = function() {
                if($scope.Data.date!=$scope.Data.currentDate)            {                $ionicLoading.show();                $scope.url=baseUrl+"historical/"+$scope.Data.date+".json?app_id="+apiKey;
                    $http.get($scope.url)                    .success(function(response) {                        $scope.historicalresult = response;                        fx.rates = response.rates;                        fx.base = response.base;                        $scope.exchangeRate=fx($scope.Data.amount).from($scope.Data.fromCurrency).to($scope.Data.toCurrency).toFixed(2);                    })                    .error(function(response, status){                        $scope.showAlert('Error!!!',response.message);                    })                    .finally(function(){                        $ionicLoading.hide();                    });            }            else{                fx.rates = $scope.result.rates;                fx.base = $scope.result.base;                $scope.exchangeRate=fx($scope.Data.amount).from($scope.Data.fromCurrency).to($scope.Data.toCurrency).toFixed(2);            }        };        $scope.doRefresh = function() {            $http.get($scope.url)                .success(function(response) {                    $scope.result = response;                                    })                .finally(function() {                    // Stop the ion-refresher from spinning                    $scope.$broadcast('scroll.refreshComplete');                });        };        $scope.showAlert = function(alertTitle,alertTemplate) {            var alertPopup = $ionicPopup.alert({                title: alertTitle,                template: alertTemplate            });            alertPopup.then(function(res) {                console.log('Log Error');            });        };
    })
    you need to create an account in OpenExchnageRates to get the api key and replace the text with your api Key and then just setting the url to request.



    Thanks...