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.