Resolve Circular Dependency Ionic

Some time in angular we face a error with name Circular Dependency, actually angular/ionic throw this error when we inject factory-1/service-1 in factory-2/service-2 and in factory-2/service-2 inject factory-1/service-1 like :


app.factory('factory1', function (factory2) {
    // Here is your other code
});

app.factory('factory2', function (factory1) {
// Here is your other code

});

We can resolve this error using $injector , like :

app.factory('factory1', function (factory2) {
    // Here is your other code
});

app.factory('factory2', function ($injector) {
var factory1 = $injector.get('factory1'); // Here is your factory1
// Here is your other code

});

input not showing invalid model values

The bug can be easily illustrated using the following example code :

<div ng-init="letters='1'">
letters = {{'' + letters}}
<input type="text" ng-model="letters" ng-pattern="/^[a-zA-Z]*$/" />
</div>

for resolve the error just user ng-model-options="{ allowInvalid: true }"  like :

<input type="text" ng-model="letters" ng-pattern="/^[a-zA-Z]*$/" ng-model-options="{allowInvalid: true}" />

Ionic Serve error

Full Error :

ionic $ module.js:338
    throw err;
          ^
Error: Cannot find module 'bower'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object. (/Users/jaswantdhayal/Desktop/Projects/Purpose it all/purposit/gulpfile.js:3:13)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)



Solution : => Go to the project directory

$rm -rf node_modules
$npm install

Convert Image into base64 by JS

When we want to upload a image in on server in cordova/ionic some time we need to convert the image in base64 formate . I've write a function which will convert your image in base64.

function convertImgToBase64URL(url, callback, outputFormat) {
 var img = new Image();
 img.crossOrigin = 'Anonymous';
 img.onload = function() {
  var canvas = document.createElement('CANVAS'),
      ctx = canvas.getContext('2d'),
      dataURL;
  canvas.height = this.height;
  canvas.width = this.width;
  ctx.drawImage(this, 0, 0);
  dataURL = canvas.toDataURL(outputFormat);
  callback(dataURL);
  canvas = null;
 };
 img.src = url;
 return url;
}

How to use :

convertImgToBase64URL(img, function(base64Img) {
 console.log(base64Img);// this is your base64 converted image     
});

Post this image on server(IONIC)

$http.post(server_url,[base64Img])

Handel this image in PHP :

   
$params = json_decode(file_get_contents('php://input'), true); get the post image

$img = imageUploadByBase64($params[0]);// this is the saved image path with image name

function imageUploadByBase64($img) {
 $randomImgName = date('Y-m-d_H-i-s').'_'.rand(0, 6000).'.png';
 $image = base64_to_jpeg($img, 'uploads/' . $randomImgName);// you need to create a directory withh name 'uploads'
 return $image;
}

function base64_to_jpeg($base64_string, $output_file) {
 $ifp = fopen($output_file, "wb");
 $data = explode(',', $base64_string);
 fwrite($ifp, base64_decode($data[1]));
 fclose($ifp);
 return $output_file;
}

Android Runtime error E/AndroidRuntime: FATAL EXCEPTION: main



   java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider: java.lang.IllegalStateException: Incorrect provider authority in manifest. Most likely due to a missing applicationId variable in application's build.gradle.
   at android.app.ActivityThread.installProvider(ActivityThread.java:5236)
   at android.app.ActivityThread.installContentProviders(ActivityThread.java:4828)
   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4768)
   at android.app.ActivityThread.access$1600(ActivityThread.java:154)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1441)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:152)
   at android.app.ActivityThread.main(ActivityThread.java:5497)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: Incorrect provider authority in manifest. Most likely due to a missing applicationId variable in application's build.gradle.
   at com.google.firebase.provider.FirebaseInitProvider.zza(Unknown Source)
   at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
   at android.app.ActivityThread.installProvider(ActivityThread.java:5233)
   at android.app.ActivityThread.installContentProviders(ActivityThread.java:4828) 
   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4768) 
   at android.app.ActivityThread.access$1600(ActivityThread.java:154) 
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1441) 
   at android.os.Handler.dispatchMessage(Handler.java:102) 
   at android.os.Looper.loop(Looper.java:152) 
   at android.app.ActivityThread.main(ActivityThread.java:5497) 
   at java.lang.reflect.Method.invoke(Native Method) 
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 




Add a single line in your build.gradle(yourProject/platforms/android/build.gradle) file 

   below   defaultConfig {

com.your.app <= Replace this with Your app bundle identifier which you can fine in you config.xml file


    defaultConfig {     
     applicationId "com.your.app" //<== Just add this line in you build.gradle file   



Transfer Google Play App form one account to account






Google provide you the facility to transfer you apps to one account to another account, For transfer you google play apps you can follow the below steps : 

Transfer apps to a different developer account(you need to fill this form) :
https://support.google.com/googleplay/android-developer/contact/appt

Get Transaction ID form here :
https://wallet.google.com/manage/?referer=https://support.google.com/googleplay/android-developer/answer/6230247?hl%3Den#transactions:filter=ALL

Need More Details about transfer you google play apps? Please find this url:
https://support.google.com/googleplay/android-developer/answer/6230247?hl=en

Sample php file for send push notification to Android devices

I've write a php file for send push notification to Android devices :

$registration_ids = array(
"fZWd8yT7uLQ:APA91bFywoAAWmXDRLkovcrR9cnIlk_ezTFSlu2nWVMv6LAffE6OC0Ox-gI_n-zPIYeLEzQ4DSKe2bowruSqNgxU3srzcMoyNAwgqmbT2IxjbgNsk7kNRm_ULrebJkcjHUGAfvIhQ3Ze"
);
$api_key = "AIzaSyCdsdFPkRPgkOL8ramcn4J2O1UEr56hMnY";

$data =  array(
            "message" => 'This is test',
            'title' => 'this is title',
            'notId'=>mt_rand(1, 115),  
            //"style" => "inbox", // if you want to show notification in inbox style
    "summaryText" => "There are %n% notifications", // if you want to show summary text in inbox style            
        );

// URL to POST to
$gcm_url = 'https://android.googleapis.com/gcm/send';

// data to be posted
$fields = array('registration_ids' => $registration_ids, 'data' => $data, );

// headers for the request
$headers = array('Authorization: key=' . $api_key, 'Content-Type: application/json');

$curl_handle = curl_init();

echo 'Notification PhP file';

// set CURL options
curl_setopt($curl_handle, CURLOPT_URL, $gcm_url);

curl_setopt($curl_handle, CURLOPT_POST, true);
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);

curl_setopt($curl_handle, CURLOPT_POSTFIELDS, json_encode($fields));

// send
$response = curl_exec($curl_handle);

echo $response;


curl_close($curl_handle);

Sample php file for send push notification to IOS devices


I've write a php file for send push notification to IOS devices


$deviceToken = "2efacf3609f7e6c59a27d0135cdce7a5e4acfe653e0b73181cc4664c3ef2bb34";
$passphrase = '123456';
$ctx = stream_context_create();

stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

$fp = stream_socket_client(
                           //'ssl://gateway.sandbox.push.apple.com:2195', $err, // for development
                           'ssl://gateway.push.apple.com:2195', $err, // for production
                           $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

if (!$fp) {
    exit("Failed to connect: $err $errstr" . PHP_EOL);
    }
  
  echo 'connecting to APNS' . PHP_EOL;
   
    // payload
 $body['aps'] = array(
                 'alert' => "This is a Message",
                 'title' => "This is a Title"
                 );
 
 
// convert payload to json
$payload = json_encode($body);

$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
$result = fwrite($fp, $msg, strlen($msg));

if (!$result) {
   echo 'Message not delivered' . PHP_EOL;
} else
    echo 'Message successfully delivered' . PHP_EOL;
}

fclose($fp);

PHP Database Connection

PHP Database Connection :

$DB  = array();
$DB['hostname'] = "localhost";
$DB['username'] = "ccodes_indihire";
$DB['password'] = "indihire@1234";
$DB['name'] = "ccodes_indihire";

function connect(){
global $DB,$CONN;
//print_array($DB);
$CONN = new mysqli($DB['hostname', $DB['username'], $DB['password'], $DB['name']);
if ($CONN->connect_errno) {
echo "Failed to connect to MySQL: (" . $CONN->connect_errno . "" . $CONN->connect_error;
}
return $CONN;

}

How to use :

$CONN = connect();


Set Current timezone in PHP :

date_default_timezone_set('Asia/Kolkata');

Get Current time in PHP :

$current_date = date('Y-m-d H:i:s');

Remove Junk characters from php array before convert array in JSON

When you creating APIs then the array contains Junk characters and this array will not convert into JSON so if you want to convert this into JSON then you've to remove the Junk characters first. You can use the following function :

function clear_junk_data($row = array()){
$array = array();
foreach($row as $key => $value){
if(is_array($value) || is_object($value)){
$array[$key] = clear_junk_data($value);
}else{
$array[$key] = preg_replace('/[^a-zA-Z0-9_ %:@\[\]\.\(\)%&<\/!#\$\^+>*=,-]/s', '', $value);
}
}
return $array;

}

How to use :

 $arr = clear_junk_data($arr);

App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.



If you are facing this issue when you are using IONIC(PhoneGap) and run the app on iPhone/iPad(IOS)

the add the following lines at the end of your info.plist file (It must be before the last  </dict> tag):


    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>

    </dict>

Splash preferences



Manage Splash Screen in IONIC(PhoneGap) or Native Project


  <preference name="SplashScreen" value="screen"/>
  <preference name="SplashScreenDelay" value="5000"/>
  <preference name="AutoHideSplashScreen" value="true" />
  <preference name="ShowSplashScreenSpinner" value="true"/>
  <preference name="FadeSplashScreen" value="true"/>
  <preference name="FadeSplashScreenDuration" value="1000"/>


For Manage Orientation

  <preference name="Orientation" value="portrait"/>

Capitalize in Javascript

You can Capitalise a string by core Javascript. I've write a function for this :

String.prototype.capitalize = function() {
return this.replace(/(?:^|\s)\S/g, function(a) {
return a.toUpperCase();
});

};

Show console.log in different colours in javascript

I've write a function for this :


function log(msg, color) {
    color = color || "black";
    bgc = "White";
    switch (color) {
        case "success":  color = "Green";      bgc = "White";       break;
        case "info":     color = "DodgerBlue"; bgc = "Turquoise";       break;
        case "error":    color = "Red";        bgc = "White";           break;
        case "start":    color = "OliveDrab"bgc = "PaleGreen";       break;
        case "warning":  color = "Tomato";     bgc = "Black";           break;
        case "end":      color = "Orchid";     bgc = "MediumVioletRed"; break;
        default: color = color;
    }

    if (typeof msg == "object") {
        console.log(msg);
    } else if (typeof color == "object") {
        console.log("%c" + msg, "color: PowderBlue;font-weight:bold; background-color: RoyalBlue;");
        console.log(color);
    } else {
        console.log("%c" + msg, "color:" + color + ";font-weight:bold; background-color: " + bgc + ";");
    }

}


You can use it like:

log("This is a Message", "error");

Sort JSON array in javascript

I've write a function for this :


function sortJson(arr, prop, dir) {
    return arr.sort(function(a,b) {       
        var propA = a[prop],propB = b[prop];
        
        if (dir=='asc') {
            return propA - propB;
        } else {
            return propB - propA;
        }
    });

}

Replace all in Javascript

I was notice that when you want to replace a string-1 to the another string-2 and the string-1 present on more the one place the the js replace function is not work properly, so here I've write a js prototype function for this :

String.prototype.replaceAll = function (find, replace) {
    var str = this;
    return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);

};

Watch Ionic menu(left or right)

.directive('watchMenu', function($timeout, $ionicSideMenuDelegate, $ionicScrollDelegate, $rootScope) {
  return {
    restrict: 'A',
    link: function($scope, $element, $attr) {
      // Run in the next scope digest
      $timeout(function() {
        // Watch for changes to the openRatio which is a value between 0 and 1 that says how "open" the side menu is
       
        $scope.$watch(function() { 
          return $ionicSideMenuDelegate.isOpenRight();
          //return $ionicSideMenuDelegate.isOpenLeft();
        }, 
          function(ratio) {
            $scope.data=ratio;
            if( ratio == 1){
              $rootScope.$broadcast('rightMenu.open');
              $ionicScrollDelegate.$getByHandle('rightMenuScroll').scrollTop();
            }else{}

          });
      });
    }
  };

});

On Click of anchor (a) open a url in inappbrowser and show loading

I've a write some functions for this :



document.onclick = function(e) {
e = e || window.event;
var element = e.target || e.srcElement;

if (element.tagName == 'A' && ((element.href.indexOf('http://') >= || element.href.indexOf('https://') >= 0)) && element.href.indexOf('//localhost:') < 0 ) {
e.preventDefault();
var ref = window.open(element.href, "_blank", "location=yes");;
ref.addEventListener('loadstart', inAppBrowserbLoadStart);
ref.addEventListener('loadstop', inAppBrowserbLoadStop);
ref.addEventListener('loaderror', inAppBrowserbLoadError);
ref.addEventListener('exit', inAppBrowserbClose);
return false;
}
}

function inAppBrowserbLoadStart(event) {
   navigator.notification.activityStart("Please Wait", "It'll only take a moment...");
}

function inAppBrowserbLoadStop(event) {
   navigator.notification.activityStop();
}

function inAppBrowserbLoadError(event) {
   navigator.notification.activityStop();
}

function inAppBrowserbClose(event) {
   navigator.notification.activityStop();
   ref.removeEventListener('loadstart', inAppBrowserbLoadStart);
   ref.removeEventListener('loadstop', inAppBrowserbLoadStop);
   ref.removeEventListener('loaderror', inAppBrowserbLoadError);
   ref.removeEventListener('exit', inAppBrowserbClose);

}

Convert time form AM/PM to 24 Hours fromat

I've made a function for this, it'll return the array of hour and minute :


function am_pm_to_hours(time) {
    var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours<10) sHours = "0" + sHours;
if(minutes<10) sMinutes = "0" + sMinutes;
//console.log(sHours + ":" + sMinutes);
    return [sHours, sMinutes];

}

Add icon in android lollipop push notification

Use this code :


PushNotification.init({
"android" : {
"senderID" : "292145204069",
"icon" : "notification_icon", // It will search for notification_icon.png in your android drawable folder
"iconColor": "#0076cb"
}

});

Play a video in iframe


Write the following code :

<iframe width="100%" height="auto" ng-if="video_url" onerror="this.style.display = 'none'" src="{{video_url | VideoUrl}}"></iframe> 
.filter('VideoUrl', ['$sce', function($sce) {
    return function(val) {
        return $sce.trustAsResourceUrl(val);
    };
}])

Show loader on InAppBrowser while loading

For InAppBrowser You've to install the plugin 'cordova-plugin-inappbrowser' :

cordova plugin add cordova-plugin-inappbrowser

For Dialogs You've to install the plugin 'cordova-plugin-dialogs' :

cordova plugin add cordova-plugin-dialogs
Then write this code for open inappbrowser :


var ref = window.open(encodeURI('http://www.google.com', '_blank', 'location=yes');

ref.addEventListener('loadstart', inAppBrowserbLoadStart);
ref.addEventListener('loadstop', inAppBrowserbLoadStop);
ref.addEventListener('loaderror', inAppBrowserbLoadError);
ref.addEventListener('exit', inAppBrowserbClose);


function inAppBrowserbLoadStart(event) {
   navigator.notification.activityStart("Please Wait", "It'll only take a moment...");
}

function inAppBrowserbLoadStop(event) {
   navigator.notification.activityStop();
}

function inAppBrowserbLoadError(event) {
   navigator.notification.activityStop();
}

function inAppBrowserbClose(event) {
   navigator.notification.activityStop();
   ref.removeEventListener('loadstart', inAppBrowserbLoadStart);
   ref.removeEventListener('loadstop', inAppBrowserbLoadStop);
   ref.removeEventListener('loaderror', inAppBrowserbLoadError);
   ref.removeEventListener('exit', inAppBrowserbClose);
}



Check GPS state (on/off) in ionic/cordova

Fist you've to install the plugin https://github.com/dpa99c/cordova-diagnostic-plugin then simply execute this code after platform ready :

Check GPS state (on/off) in ionic/cordova

cordova.plugins.diagnostic.isLocationEnabled(function(enabled){
    console.log("Location is " + (enabled ? "enabled" : "disabled"));
}, function(error){
    console.error("The following error occurred: "+error);
});


Check WiFi is enable or not?

cordova.plugins.diagnostic.isWifiEnabled(function(enabled){
    console.log("WiFi is " + (enabled ? "enabled" : "disabled"));
}, function(error){
    console.error("The following error occurred: "+error);
});

Check device has a camera AND the application is authorized to use it. or not?

cordova.plugins.diagnostic.isCameraEnabled(function(exists){
    console.log("Device " + (exists ? "does" : "does not") + " have a camera");
}, function(error){
    console.error("The following error occurred: "+error);
});

Enables/disables WiFi on the device

cordova.plugins.diagnostic.setWifiState(function(){
    console.log("Wifi was enabled");
}, function(error){
    console.error("The following error occurred: "+error);
},
true);

Checks the device has Bluetooth capabilities and if it has then Bluetooth is on or off?

cordova.plugins.diagnostic.isBluetoothEnabled(function(enabled){
    console.log("Bluetooth is " + (enabled ? "enabled" : "disabled"));
}, function(error){
    console.error("The following error occurred: "+error);
});


Enables/disables Bluetooth on the device

cordova.plugins.diagnostic.setBluetoothState(function(){
    console.log("Bluetooth was enabled");
}, function(error){
    console.error("The following error occurred: "+error);
},
true);

Publish Ionic App on Play Store in Ionic/Cordova


When You want to publish your app on play store, First thing you have to do is 'create a keystore file'
(Make sure, when you've published app using a keystore then for publish this particular app next version, you must need the same keystore file, without will not able to publish the new version of this app)

1.) Create a keystore file by cmd :

keytool -genkey -v -keystore keystore_name.keystore -alias your_app_alias -keyalg RSA -keysize 2048 -validity 10000

After this you've to answer some question and then you keysore file will created in root folder of your   project.

2.) To sign the unsigned APK, run the jarsigner tool which is also included in the JDK:


jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore keystore_name.keystore android-release-unsigned.apk alias_name

3.) Finally, you need to run the zip align tool to optimise the APK file :

First you to go into the zipalign folder, eg.:
    For Windows :
             cd /path/to/Android/sdk/build-tools/VERSION
             zipalign -v 4 android-release-unsigned.apk android_store_apk.apk

    For OS X :
             cd Users/UserName/Library/Android/sdk/build-tools/VERSION
             ./zipalign -v 4 android-release-unsigned.apk android_store_apk.apk


Now You can Publish android_store_apk.apk on the play store.