angularjs cancel resource request

Its a only trick which works for me very well:

Here is your function in controller which get the search results by submitting a form:

var methodCallCounter = 0;

$scope.getMyResults = function (){
     ++methodCallCounter;
     // Calling your service here and getting data
    Service.getResults({search: $scope.searchData, counter:methodCallCounter}, function (response) {
        if(methodCallCounter == response.counter){
            // Show your search results to user
        }else{
          // Do nothing, you can remove this else block
       }
    });
}

The idea is
- Use a counter variable in method call
- Send this counter variable with request
- Return same counter variable in response from server
- Match value of both counter value (client side and response)
- If value of both are same show results
- Else do nothing

Any doubts, please ask in comments.

ionic scroll for desktop

Use overflow-scroll class as mentioned in the code below:


<ion-content class="scroll-content ionic-scroll  has-header overflow-scroll">
</ion-content>


It will work in Desktop browsers as well as mobile.

SEVERE: Error listenerStart

Solution to debug:

SEVERE: Error listenerStart

Occurs when an exception is thrown in the contextInitialized method of a ServletContextListener

SEVERE: Error filterStart

Occurs when an exception is thrown in the init method of a Filter
Unfortunately by default, tomcat won’t provide you with any details about the cause of the error. Infact it wont even tell you which filter or listener is failing. This can be big problem in applications of significant size that have many filters and listeners configured. Fortunately there is a solution. In your webapplication’s WEB-INF/classes folder you can create a logging.properties file with the following contents

org.apache.catalina.core.ContainerBase.[Catalina].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler


Now you will be presented with the stacktrace

angularjs $scope vs var

Question is when to use $scope vs var and vice versa?

Ans: Answer is very simple and must be followed.

When You want two way binding or your variable is used in the UI part use $scope otherwise var.

For example:


var a = 10;

$scope.b = x * 5;

{{x}} - undefined

{{y}} - 50


So the conclusion is if your variable not interact to view part then it must be declared as var.
 
 
 
 

AngularJS App Structure

I have created many applications based on AngularJS and Structure what I follows is:

testapp (Root folder of App)

    - js
         - controllers
         - services
         - directives
    - lib
         - angular.min.js
         - jquery.min.js
         - -- many more third party libraries
    - views
         - login
           - login.html
         - my-profile
           - profile.html
    - i18n
         - en.jsom
    - images
        - logo.png
    - css
        - bootstrap.min.css
        - custom.css
    - fonts
        - -- all font files --
    - data
        - any default data json files
    - app.js
    - index.html

jQuery select2 editable with dynamic data

Your Javascript code:

EmpType.getList(function(response){
            $scope.empTypes=response.data;
            var typesArr = new Array();
            for (var int = 0; int <$scope.empTypes.length; int++) {
                var jsonObj = {
                        "id": $scope.empTypes[int].id,
                        "text": $scope.empTypes[int].name
                };
                typesArr[int] = jsonObj;
            }
           
            $("#empTypes").select2({
                createSearchChoice:function(term, data) {
                    if ($(data).filter(function() {
                        return this.text.localeCompare(term)===0;
                    }).length===0)
                    {return {id:term, text:term};}
                },
                data:typesArr
            });
           
        });
 
Your HTML code:
 

<input type="text" name="empTypes" id="empTypes"
                    class="form-control" />
 
and don't forget to include below files:
 
    <link rel="stylesheet" href="css/select2.css" />
    <link rel="stylesheet" href="css/select2-bootstrap.css"/> 
    <script type="text/javascript" src="lib/select2.min.js"></script>

jquery file upload


Use below javascript function:


function uploadFile(fileObj) {
    var formData = new FormData();
    formData.append("file", fileObj.files[0]);
   
    var url = "sv/upload-file.php?action=upload-image";

    $.ajax({
        type : "POST",
        url : url,
        cache : false,
        contentType : false,
        processData : false,
        data : formData,
        success : function(json) {
            console.log(json);   
       },
        error : function (err){
            console.log(json);
        }
    });
}


And in Html code:

<input type="file" onchange="uploadFile(this)" />


Write your server side code in php, java or any other language.

If any doubt ask in comments.

open ionic app from browser

Follow the instructions as given in below link:


http://mcgivery.com/using-custom-url-schemes-ionic-framework-app/

 

Single Sign on saml 2.0 for ionic mobile apps

I did SSO using https://github.com/onelogin/java-saml 

It was working good for my website. But the question was how can I integrate it with my mobile app.

then I found a ionic plugin that best suited for my requirements.

http://mcgivery.com/using-custom-url-schemes-ionic-framework-app/

How I used this plugin:

There are two files in my web project index.jsp and consume.jsp.

1. SSO starts from index.jsp (This is the start point of my web app).
 2. Then redirects to organization page which according to saml 2.0 configuration which I am not mentioning here right now.
3. User fills the credentials and hit the submit button.
4. Response come back to consume.jsp.
5. In consume.jsp I have checked login is successful or not.
6. If login is successful then I redirect to home.jsp otherwise error message.

This was right in the case of web app. But the question was how can I achieve this is mobile app.

Answer is here:

http://mcgivery.com/using-custom-url-schemes-ionic-framework-app/

Install this plugin in your ionic app as instructions give in this link.

Write somewhere in body tag of consume.jsp:

<a href="ionicapp://" id="myLink">Open my app</a>

and between the code of successful login write:

<script type="text/javascript">
      document.getElementById('myLink').click();
</script>

This is a trick. What this code will do is: It will open your mobile app on successful login :).

Ask questions in comments if any problem you face.

angularjs show initials of user first name and last name as profile icon

Use below directive:

app.directive('showInitials', function() {
    return function(scope, element, attrs) {
        var userVals = attrs.showInitials;
        var arrUserVals = userVals.split(',');
        if(arrUserVals[0] == "" || arrUserVals[0].lastIndexOf('default-image.png') != -1){
            var initialStr = (arrUserVals[1].substr(0, 1) + "" + arrUserVals[2].substr(0, 1)).toUpperCase();;
            var initialHtml = '<div class="avatar-framed text">'+initialStr+'</div>';
            $(element).parent().html(initialHtml);
        }
    }
});

Use this directive in your html like:

<img ng-src='{{user.picture}}' data-holder-rendered="true"
                                class="avatar-framed text"
                                show-initials="{{user.picture}},{{user.firstName}},{{user.lastName}}">

In css file make sure following classes exists:

.avatar-framed {
    display: inline-block;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
    background-color: white;
    line-height: 0px;
    color: white;
    background-color: #ccc;
    vertical-align: middle;
    text-align: center;
}

.avatar-framed.text {
    width: 50px;
    height: 50px;
    border: 2px solid white;
    -webkit-box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2);
    -moz-box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2);
    box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2);
    line-height: 50px;
    font-size: 20px;
}

.avatar-frame, .avatar-frame img {
    width: 50px;
    height: 50px;
    -webkit-border-radius: 30px; /* Saf3+, Chrome */
    border-radius: 30px; /* Opera 10.5, IE 9 */
    /*-moz-border-radius: 30px;  Disabled for FF1+ */
}

angularjs set page title

Use below code to dynamically set page title depending on your state or route:

in app.js

...
...
.state('signup', {
            url: "/signup",
            controller: 'SignUpCtrl',
            templateUrl: 'views/signup/signUp.html',
            pageTitle: 'SignUp'
        });
...

app.run(function($rootScope, $state) {
  $rootScope.$on('$stateChangeStart', function(event, current) {
      $rootScope.pageTitle = current.pageTitle;
   })
});

in html:

<html ng-app="app"> 
 <head> 
 <title>{{ pageTitle }}</title>
 ... 

AngularJS Login and Authentication in each route and controller

Use below code

 app.run(function($rootScope, $state, localStorageService) {
  $rootScope.$on('$stateChangeStart', function(event, current) {
      if (current.url != '/login' && current.url != '/signup' &&
              current.url != '/createPassword' && current.url !=
                  '/forgotPassword' && localStorageService.get('user') == null) {
          event.preventDefault();
          $state.go('login');
      }
  })
});


ionic offline storage

There are many ways to offline storage in hybrid/ionic app:

1. Cookies
2. Offline Storage
3. Sqlite Database


1. Cookies : Consider this method if size of data is very less. Mostly cookies are used only for login purposes.


2. Offline Storage: This method used key/value pair to store data.

Following code will store data in memory of user's webview/browser:

if(window.localStorage !='undefined'){
        localStorage.setItem("user-name", "Jason sta");
}

To retrieve above saved data we have to right below code:

var userName = localStorage.getItem("user-name");

3. Sqlite Database: 

There are two ways we can create sqlite database in mobile browser/webview.

A. Using Javascript/html5 code

B. Using Java code:

After creating database we have to copy the database into source code of mobile app before creating apk/ipa file.


ionic slow scrolling

We always use ng-repeat to populate a list in our hybrid apps Which is not a good idea.

If list size is very large then we should use collection-repeat instead of ng-repeat.

This will drastically improve the performance of your list. The idea behind collection-repeat is that It will contain the html elements in DOM what you seeing actually.

ionic side menu logo in header

Use below code in main template html file.

<ion-side-menus expose-aside-when="large" enable-menu-with-back-views="true">
        <ion-pane ion-side-menu-content>
        </ion-pane>
      <ion-side-menu side="left">
            <header class="bar bar-header bar-positive">
                <div>
                      <img class="margin-top:4px; float:left" src="images/logo.png"/>
                </div>

            </header>
            <ion-content class="has-header">
           </ion-content>
        </ion-side-menu>
</ion-side-menus>

and don't forget to write attribute "has-header" in your child templates files like:

<ion-view class="bubble-background" hide-back-button="true">
    <ion-nav-buttons side="left">
        <button menu-toggle="left" class="button button-icon icon " ></button>
      </ion-nav-buttons>
    <ion-content class="has-header has-footer">
     </ion-content>
</ion-view>

ionic footer bar


<ion-footer-bar class="bottom-banner bar-positive">
            <h1 class="title">
                   This is the footer of ionic app
            </h1>
</ion-footer-bar>


In the side menu template above code should be use like:

<ion-side-menus expose-aside-when="large" enable-menu-with-back-views="true">
        <ion-pane ion-side-menu-content>
            <ion-nav-bar class="bar-positive nav-title-slide-ios7">
                <ion-nav-buttons side="left">
                    <button class="button button-icon button-clear ion-navicon" toggle="left"></button>
                </ion-nav-buttons>
   
                <ion-nav-back-button class="button-clear">
                    <i class="icon ion-chevron-left"></i>
                </ion-nav-back-button>
   
            </ion-nav-bar>
            <ion-nav-view name="main" animation="slide-left-right">
           </ion-nav-view>
            <ion-footer-bar class="bottom-banner bar-positive">
                <h1 class="title">
                      This is the footer of ionic app
                </h1>
            </ion-footer-bar>
        </ion-pane>

       <ion-side-menu side="left">
            <header class="bar bar-header bar-positive">
             </header>
            <ion-content class="has-header">
       </ion-content>
        </ion-side-menu>
       
    </ion-side-menus>


And don't forget to user attribute "has-footer" in your child templates/views like:

<ion-content class="has-header has-footer">
</ion-content>

angularjs controller in directive

app.directive('customButton', function() {
  return {
    restrict: 'A',
    scope: true,
    template: '<button ng-click="clickMe()" type="button">Click Me</button>',
    replace: true,
    controller: function($scope, $element) {
      $scope.clickMe = function() {
         alert("yes Its working"); 
      }
    }
  }
});

Use this directive in html page like:

<span custom-button></span>

So above span will be replaced by html value used in template attribute of directive. And you will see a button labeled "Click Me".

When  you clicked on that button you should see a alert.


angularjs directive hide element

Create a directive in app.js like below code:


app.directive('hideElement', function() {
     return function(scope, element, attrs) {
           element.hide();
     }
});


and use in your html page like

<a href="/#employees" hide-element>Employees</a>

You can also inject any service in this directive like:

app.directive('hideElement', function(EmployeeService) {
     return function(scope, element, attrs) {
         // Get data using employee service
         // and hide element according to any condition

           element.hide();
     }
});

AngularJS get attribute value in directive

<a check-permission permissioncode="BILLING_MANAGE">Billing</a>


In above line directive name is check-permission and we want value of attribute permissioncode in directive.

Using below code we can get the value of attribute permissioncode:

app.directive('
checkPermission', function() {
    return function(scope, element, attrs) {
        attrs.$observe('permissioncode', function(permission) {
              alert(permission)
        });
    }
});

Pnotify center position

Apply below class:

.ui-pnotify{
   left: 50%;
   margin-left: -150px;
}

Note: Margin left should be half of your div width.

Eg: If div width is 300px then margin left will be -150px.

CSS horizontal centering of a fixed div

Apply below class to your div which is position fixed:

.div-position-fixed-centered-align{
   left: 50%;
   margin-left: -150px;
}

Note: Margin left should be half of your div width.

Eg: If div width is 300px then margin left will be -150px.

Restart Ionic application programmatically

Please try below code, Its working for me:

         $state.go("your_main_state_name_here");
          $ionicHistory.clearHistory();
          setTimeout(function (){
                 $window.location.reload(true);
          }, 100);

Cordova plugin commands

Add a plugin in app:

Cordova plugin add <plugin>

Search a plugin:

Cordova plugin search <splashscreen>

See the list of plugins added in your app:

Cordova plugin list

Run ionic

​​
​​
export ANDROID_HOME="$HOME/install/adt-bundle-linux-x86_64-20140702/sdk"
 
export PATH="$HOME/install/adt-bundle-linux-x86_64-20140702/sdk/tools:$ANDROID_HOME/platform_tools:$PATH"
Don't run below commands with sudo
ionic start myIonicApp tabs
​​
cd myIonicApp ionic platform add android ionic build android ionic emulate android
Ionic examples:
http://codepen.io/ionic/public-list/

Run npm update -g ionic to update
Open ionic app in browser:
ionic serve
​​
Open ionic app in browser on specific port

​​
ionic serve 8080 8100

Enable cookies in your ionic app

Go to

/node-v0.10.29/ionicnew/platforms/android/src/com/ionicframework/< you package name>

then open CordovaApp.java

insert below line of code:

CookieManager.setAcceptFileSchemeCookies(true);      


in ​onCreate() method like:

​super.onCreate(
savedInstanceState);
super.init();
​​
CookieManager.setAcceptFileSchemeCookies(true);       
// Set by <content src="index.html" /> in config.xml
super.setIntegerProperty("splashscreen", R.drawable.screen);
super.loadUrl(Config.getStartUrl());
 
and import following package
 
​import android.webkit.CookieManager;



​ Open ionic app in browser on specific port

​ionic serve 8080 8100

Why Ionic is best for hybrid mobile apps development?

Ionic is an UI framework which is build to create hybrid mobile apps based on Html5.

Unlike a responsive framework, Ionic is packed with very native-styled mobile UI elements and layouts that you get with a native SDK on iOS or Android. Also, Ionic is built on the top of popular AngularJS framework from Google to utilize AngularJS power.

Why Ionic

Build apps with the web platform. Using HTML, CSS, and JavaScript, you can make
hybrid apps that behave like native like mobile apps.


Built with AngularJS. For people familiar with AngularJS (or even another JavaScript
framework like Ember), Ionic is a perfect choice. Ionic is built alongside Angular, which
allows you access to all of Angular’s features as well as any of the many thousands of
Angular modules for additional features. Ionic also uses the popular ui.router module
for navigation, because Angular’s default routing module lacks some features.

Uses modern techniques. Ionic was designed to work with modern CSS3 features, like
animations. Mobile browsers generally have better support for the latest web platform
specifications, which allows you to use those features as well.

Powerful CLI tools. With the Ionic command line tool, you can quickly manage
development tasks such as previewing the app in a browser, emulating the app, or
deploying an app to a connected device. It helps with setting up and starting a project
as well.

Ionic ecosystem. Ionic also provides a rich ecosystem of features that make
development much easier. The Ionic Creator service allows you to use a drag and drop
interface to design and export an app. An upcoming service for remotely building and
deploying apps is also in development. In short, Ionic is all about creating not just the
basic tools for making hybrid apps but also the development tools that will help you
create them efficiently.


 

Must have plugins for hybrid app

org.apache.cordova.network-information

Using this you can identify the network/internet information of device. Very useful to identify online/offline mode.

​​
org.apache.cordova.inappbrowser
Using this plugin you can open external links in new browser window in your app. So that by pressing back button on your device, will show your app again.
​​
​​
org.apache.cordova.splashscreen

You can show splash screen to user at the time of app start.

com.phonegap.plugins.pushplugin

Your application can receive push notifications.

org.apache.cordova.dialogs


Show alert boxes like native apps.

https://github.com/brodysoft/Cordova-SQLitePlugin


This is sqlite plugin. Using this you can store offline data in your hybrid app.

nl.x-services.plugins.toast

This one used to show a toast message. Toast message hides after sometime automatically.

Top hybrid mobile framework

IONIC

The best framework to create hybrid apps in my opinion. I am using this to create hybrid apps.

Great examples are provide by IONIC community. There are separate examples available which you need to develop a app.

Good app structure. You can separate your html views, js controlles and js services.

Its worked on angularJS which is a plus point for every web developer. These days angularJS used in every SPA (Single page application).

No new technology required to work on ionic. Only we need knowledge of html5, css and javascript.

IONIC is one of the most promising HTML 5 mobile application frameworks. Built using SASS, it provides many UI components to help develop rich and interactive apps. It uses the JavaScript MVVM framework, AngularJS to power apps. Two-way data binding, interaction with backend services and APIs makes AngularJS a mobile developer’s common choice. With the coming release of AngularJS 2.0, focused on mobile, it’s sure to gain even more popularity.
The team at IONIC will soon be introducing an easier way to create IONIC apps with IONIC creator. This will be released soon and will have drag and drop functionality to get started with app development in minutes.


Mobile Angular UI

Mobile Angular UI is an HTML 5 framework which uses bootstrap 3 and AngularJS to create interactive mobile apps.
The main features of Mobile AngularUI include:
  • Bootstrap 3
  • AngularJS
  • Bootstrap 3 mobile components such as switches, overlays and sidebars which are missing in normal bootstrap.
  • AngularJS modules such as angular-route, angular-touch and angular-animate
Responsive media queries are stripped out of bootstrap as separate files, you only need to include what you need. Mobile Angular UI doesn’t have any jQuery dependencies, all you need are some AngularJS directives to create awesome mobile user experiences.
Take a look at the Mobile Angular UI demo page to see it in action. If you want to dig deeper, I would recommend reading our article on getting started with Mobile Angular UI.

Intel XDK

Intel XDK is a cross platform application tool developed by Intel. Getting started with Intel XDK is easy, all you need is to download their application which is free and available for Linux, Windows and Mac. It provides a number of templates to get started and supports a number of UI frameworks such as Twitter bootstrap, jQuery Mobile and Topcoat.
Intel XDK provides a live preview on the connected device whilst you are developing along side many other useful tools.
On a personal note, I think development using Intel XDK was the easiest. It uses a drag and drop approach, although it does create a lot of unnecessary code.

Appcelerator Titanium

Appcelerator’s Titanium is an open source mobile application framework that provides an environment to create native apps for several mobile platforms
Titanium is a complete solution for creating hybrid mobile apps with all you need in one place. To get started with Titanium download Titanium studio. The Titanium SDK is equipped with a number of mobile platform APIs and Cloud service to use as an app backend. It comes with platform independent APIs which makes it easier to access phone hardware.
Titanium uses Alloy, a MVC framework to enable rapid development of mobile apps. Modules created using Alloy are easy to reuse across different apps, hence significantly reducing the development time and the lines of code.

Sencha Touch

Sencha Touch is an HTML 5 mobile app framework for creating apps for several platforms including iOS, Android and Blackberry. It has been in existence for some years now and is popular among hybrid mobile application developers.
Sencha Touch scores highly against it’s competitors by providing a native look and feel across all of the platforms it supports.
Getting started with Sencha Touch isn’t that difficult but in order to get the best out of Sencha Touch, one needs to invest a considerable amount of time.

Kendo UI

Telerik’s Kendo UI is an HTML 5 framework for creating cross platform mobile applications. Kendo UI relies heavily on jQuery and has a number of jQuery based widgets.
Learning Kendo UI is not difficult, developers familiar with jQuery will find Kendo UI easy to learn. Kendo UI has open sourced most of Kendo UI’s toolset and JavaScript framework features. However most of the commonly used widgets are still under a commercial license.

PhoneGap

PhoneGap is the odd one out in this list as it’s not a framework for creating an app, but for packaging and releasing an app. PhoneGap is based on the open source Cordova and is the commercial version owned by Adobe. With a dedicated support team, PhoneGap is popular amongst many mobile developers.
You can use any choice of JavaScript or UI frameworks to get started with PhoneGap. jQuery Mobile alongside KnockOut.js or AngularJS is a nice combination. Once you are done with your code, PhoneGap takes it from there and wraps it based on the intended platform. Applications built using PhoneGap use a web view to render their content. PhoneGap has a minimal set of web APIs to access phone hardware features and it’s possible to write custom plugins to suit requirements.
 
 
 

Why hybrid apps?

1. You can develop hybrid apps using your simple web skills: Html5, css, Javascript.
2. No separate budget required for iOS and Android.
3. Development cost is reasonable compared to native apps.
4. Same code base can be used for web application.
5. You can test them in browser like google chrome/Safari.
6. Large community to support.

Cordova show alert dialog

To show alert box in cordova hybrid app use:

navigator.notification.alert('This is the alert box', null, '', 'Close');

Ionic width classes

CSS Width Class      CSS Offset Class        Width
.col-10                             .col-offset-10                   10%
.col-20                             .col-offset-20                   20%
.col-25                             .col-offset-25                   25%
.col-33                             .col-offset-33                   33.3%
.col-50                             .col-offset-50                   50%
.col-67                             .col-offset-67                   66.6%
.col-75                             .col-offset-75                   75%
.col-80                             .col-offset-80                   80%
.col-90                             .col-offset-90                   90%

Ionic pass more than one argument in go()


$state.go("main.user", {id:10, type:'Manager'});

Ionic disable back on particular view

Ionic disable back on particular view:

$ionicHistory.nextViewOptions({
     disableAnimate: true,
     disableBack: true
});

Ionic modal set backdrop click false

Use below code:

$ionicModal.fromTemplateUrl('views/login-page.html', {
        scope: $scope,
        backdropClickToClose: false
    }).then(function(modal) {
        $rootScope.modal = modal;
 });

Ionic clear history

To clear history in ionic use

$ionicHistory.clearHistory();

Initialize ionic on device ready

1. Remove ng-app attribute from <HTML> tag.

2. Add below code in your index.html:

<script>
     // Wait for Cordova to load
     document.addEventListener("deviceready", onDeviceReady, false);

     // Cordova is ready
     function onDeviceReady() {
          app.services = angular.module('services', ['ngResource']);
          angular.bootstrap(document, ['ionicApp']);
     }
</script>


Ionic navbar search

Html:

<search-bar ng-model="search"></search-bar>

app.js:

.directive('searchBar', [function () {
  return {
    scope: {
      ngModel: '='
    },
    require: ['^ionNavBar', '?ngModel'],
    restrict: 'E',
    replace: true,
    template: '<ion-nav-buttons side="right">'+
            '<div class="searchBar">'+
              '<div class="searchTxt" ng-show="ngModel.show">'+
                  '<div class="bgdiv"></div>'+
                  '<div class="bgtxt">'+
                    '<input type="text" placeholder="Search..." ng-model="productObject.searchAgenda">'+
                  '</div>'+
                '</div>'+
                '<i class="button button-clear" ng-class="{\'icon-disabled-opacity\' : showdate}" ng-click="updateSelection();" title="Show all dates">All</i>'+
            '</div>'+
          '</ion-nav-buttons>',
   
    compile: function (element, attrs) {
      var icon=attrs.icon
          || (ionic.Platform.isAndroid() && 'ion-android-search')
          || (ionic.Platform.isIOS()     && 'ion-ios7-search')
          || 'ion-search';
      angular.element(element[0].querySelector('.icon')).addClass(icon);
     
      return function($scope, $element, $attrs, ctrls) {
        var navBarCtrl = ctrls[0];
        $scope.navElement = $attrs.side === 'right' ? navBarCtrl.rightButtonsElement : navBarCtrl.leftButtonsElement;
       
      };
    }
   
  };
}])

yourCTRL.js:

app.controller('searchBarCtrl', function($scope,$ionicNavBarDelegate){
  var title, definedClass;
  $scope.$watch('ngModel.show', function(showing, oldVal, scope) {
    if(showing!==oldVal) {
      if(showing) {
        if(!definedClass) {
          var numicons=$scope.navElement.children().length;
          angular.element($scope.navElement[0].querySelector('.searchBar')).addClass('numicons'+numicons);
        }
       
        title = $ionicNavBarDelegate.getTitle();
        $ionicNavBarDelegate.setTitle('');
      } else {
        $ionicNavBarDelegate.setTitle(title);
      }
    } else if (!title) {
      title = $ionicNavBarDelegate.getTitle();
    }
  });
});


Ionic remove back button

To remove back button use hide-back-button="true" on ion-view


<ion-view title="{{navTitle}}" class="bubble-background" hide-back-button="true">

Ionic cache false for particular state

Use below code to cache false for particular state:

.state('main.emp', {
            cache : false,
            url: '/emp',
            views: {
                'main': {
                  templateUrl: 'views/emp-list.html',
                  controller : 'EmpCtrl'
                }
            }
  })

Ionic show option button

To add option button using ionic your code should look like:

<ion-list can-swipe="true">
        <ion-item ng-repeat="item in itemList">
              <ion-option-button class="button-stable" ng-click="showDetail(item)">Details</ion-option-button>

        </ion-item>
 </ion-list>

When you swipe your item from right to left then you can see option button "Details".

Ionic fixed search bar

To add fixed search bar in ionic your html code should look like:

<ion-header-bar class="bar bar-subheader item-input-inset">
      <label class="item-input-wrapper search">
        <i class="icon ion-search placeholder-icon"></i>
        <input placeholder="Search..." ng-keyup="searchList($event)" type="text">
      </label>
 </ion-header-bar>

When user starts typing in search field then searchList() method will call. You can change this in your code according to your requirements.

Ionic infinite scroll

Your html content should look like this:

<ion-content class="has-header">
     <ion-list>
        <ion-item ng-repeat="item in arrItemValues track by $index">
            {{item}}
        </ion-item>
    </ion-list>
    <ion-infinite-scroll ng-if="isMoreItems" on-infinite="updateList()" distance="10%">
</ion-infinite-scroll>
</ion-content>

When user scroll from bottom then updateList() method will call.


You can write your JS code in updateList() method to update your list.

Ionic pull to refresh

Your html content should look like this:

<ion-content class="has-header">
    <ion-refresher pulling-text="Refreshing List" on-refresh="refreshList()">
    </ion-refresher>
    <ion-list can-swipe="true">
        <ion-item ng-repeat="item in arrItemValues track by $index">
            {{item}}
        </ion-item>
      </ion-list>
</ion-content>

When user pull to refresh on html page the refreshList() method will call.

You can write your JS code to populate the list.




Ionic Leaving and entered state issue

To fix this issue remove abstract attribute from state mappings.

Its works for me.

Ionic show loader in each ajax/http request

Add below lines of code in run section of your app.js

$rootScope.$on('loading:show', function() {
     $ionicLoading.show({template: '<ion-spinner icon="spiral"/>'})
 })

 $rootScope.$on('loading:hide', function() {
      $ionicLoading.hide()
 })


Add below interceptor in config section of your app.js

$httpProvider.interceptors.push(function($rootScope, $injector, $q) {
        return {
            request: function(config) {
              $rootScope.$broadcast('loading:show');
              return config
            },
            response: function(response) {
              var $http = $http || $injector.get('$http');
              if($http.pendingRequests.length < 1) {
                $rootScope.$broadcast('loading:hide');
              }
              return response;
            },
            requestError: function(rejectReason) {
              $rootScope.$broadcast('loading:hide');
              return $q.reject(rejectReason);
            },
            responseError: function(rejectReason) {
              $rootScope.$broadcast('loading:hide');
              return $q.reject(rejectReason);
            }
        }
    });

in app.js It may look like:

app.run(function($ionicPlatform, $rootScope, $ionicLoading) {
        $ionicPlatform.ready(function() {
            if(window.StatusBar) {
                // org.apache.cordova.statusbar required
                StatusBar.styleDefault();
                StatusBar.overlaysWebView(true);
            }
        });

        $rootScope.$on('loading:show', function() {
          $ionicLoading.show({template: '<ion-spinner icon="spiral"/>'})
        })

        $rootScope.$on('loading:hide', function() {
          $ionicLoading.hide()
        })
 })

.config(function($stateProvider, $urlRouterProvider, $httpProvider) {

$stateProvider

  .state('app', {
    url: '/app',
    abstract: true,
    templateUrl: 'templates/menu.html',
    controller: 'AppCtrl'
  })

  .state('app.softwareCostEstimation', {
    url: '/softwareCostEstimation',
    views: {
      'menuContent': {
        templateUrl: 'templates/softwareCostEstimation.html',
        controller: 'SoftwareCostEstimationCtrl'
      }
    }
  })

----
----

$urlRouterProvider.otherwise('/app/softwareCostEstimation');

  $httpProvider.interceptors.push(function($rootScope, $injector, $q) {
        return {
            request: function(config) {
              $rootScope.$broadcast('loading:show');
              return config
            },
            response: function(response) {
              var $http = $http || $injector.get('$http');
              if($http.pendingRequests.length < 1) {
                $rootScope.$broadcast('loading:hide');
              }
              return response;
            },
            requestError: function(rejectReason) {
              $rootScope.$broadcast('loading:hide');
              return $q.reject(rejectReason);
            },
            responseError: function(rejectReason) {
              $rootScope.$broadcast('loading:hide');
              return $q.reject(rejectReason);
            }
        }
    });

});

Ionic remove back button text

Just add below lines in your app.js

$ionicConfigProvider.backButton.text('Back').icon('ion-chevron-left');
$ionicConfigProvider.backButton.previousTitleText(false).text(''); // Removes back button text 

It may be like as:

app.run(function($ionicPlatform, $rootScope, $ionicLoading) {
   // your code
})

.config([...]){
   $ionicConfigProvider.backButton.text('Back').icon('ion-chevron-left');
   $ionicConfigProvider.backButton.previousTitleText(false).text(''); // Removes back button text
}