Categories
AngularJS Career Code Area Java Script Tips and Tricks

Getting Query String Values Without a Hash in the URL

$location.search() returns empty? Angular does not remove the query before the hash bang in URL. According to AngularJS documentation,  hash bang URL format is:

http://example.com/#!/bar?baz=23

So if you have no hash bang in your URL (e.g. http://example.com/bar?baz=23), and try to get query string value, then you can use this snippet.

function getQueryParams(queryParam, url) 
{
        var pageUrl = url || window.location.search.substring(1);
        var urlVariables = pageUrl.split(/[&||?]/);
        var response = null;

        for (var i = 0; i < urlVariables.length; i += 1) {
            var param = urlVariables[i];
            var paramName = (param || '').split('=');

            if (paramName[0] === queryParam) {
                response = paramName[1];
            }
        }
        return response;
}
    
console.log(getQueryParams('baz', 'http://example.com/bar?baz=23'));

This code is also with pure JavaScript (withour AngularJS).

Categories
AngularJS Career

How to Fix Error: ngRepeat:dupes Duplicate Key in Repeater in AngularJS

Error: ngRepeat:dupes Duplicate Key in Repeater is the most common problem we are facing when we work with AngularJS. Why does it happen? It’s happened when there is any duplicate key is exist in ngRepeat expression. By default, AngularJS uses keys to populate the dom elements. So if there is any duplicate key found in ngRepeat expression, then the error happens.

Example:

Now assume we have data like this format. Here 5 is the duplicate number. And when we try to use ngRepeat expression and we will get Error: ngRepeat:dupes Duplicate Key in Repeater.

$scope.numbers = [1, 2, 3, 4, 5, 5];
<p ng-repeat="number in numbers">
    {{ number }}
</p>

To fixed this problem you have to use track by $index with ng-repeat.

<p ng-repeat="number in numbers track by $index">
    {{ number }}
</p>

The problem will be solved after using track by $index with ng-repeat.

Categories
AngularJS Code Area

Dynamic Page Title with AngularJS

Page title is the most common and important fact for a website as well as an application which influence the SEO score of a website. Generally, page title needs to change for each page depends on the page content. This article is for creating dynamic page title with AngularJS and ui-router.

At first, you need to download ui-router module and load in your application. Then configure your applications routes by using ui-router module.

Example of Dynamic Page Title with AngularJS:

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

    $urlRouterProvider.otherwise('/')

    $stateProvider.state('home', {
        url: '/',
        templateUrl: 'home.html',
        data: {
            title: 'Home Page'
        }
    });

    $stateProvider.state('about', {
        url: '/about',
        templateUrl: 'about.html',
        data: {
            title: 'About Me'
        }
    });

    $stateProvider.state('blog', {
        url: '/blog',
        templateUrl: 'blog.html',
        data: {
            title: 'Personal Blog'
        }
    });

    $stateProvider.state('contact', {
        url: '/contact',
        templateUrl: 'contact.html',
        data: {
            title: 'Contact Me'
        }
    });
});

From the above code snippet, you can see I have configured my routing by using ui-router. According to ui-router I have used $stateProvider.state to create my individual route. And I added the title for each state which I will show into the browser.

app.run(['$rootScope', '$state',
        function ($rootScope, $state) {
            $rootScope.$on('$stateChangeSuccess', function () {
                $rootScope.title = $state.current.data.title;
            });
        }
    ]
);

And this snippet of code will execute while angular application will run. With the $rootScope.$on getting the successfully state changes ($stateChangeSuccess) and taking the each state’s title and assign into $rootScope.title.

And then modify your title tag to include ng-bind:

<title ng-bind="(title || 'Home') + ' - AngularJS Dynamic Title'">
   AngularJS Dynamic Title
</title>

This is really simple and easy way to set Dynamic Page Title with AngularJS. Here I have included a demo and source code link for you. Hope these will be helpful for you.

Demo Link: https://sohelrana820.github.io/dynamic-page-title-with-angular-js/#/

Source Code: https://github.com/sohelrana820/dynamic-page-title-with-angular-js

Categories
AngularJS Code Area Java Script

Download and then Print PDF File in AngularJS

Sometime developer need to download PDF file and print that pdf document. Here I have shared a code snippet for download pdf then print that pdf using angularJS.

$scope.printPdf = function (uuid){
        $http({
            url : 'PDF_URL',
            method : 'GET',
            headers : {
                'Content-type' : 'application/pdf'
            },
            responseType : 'arraybuffer'
        }).success(function(data, status, headers, config) {
            var pdfFile = new Blob([ data ], {
                type : 'application/pdf'
            });
            var pdfUrl = URL.createObjectURL(pdfFile);
            var printwWindow = $window.open(pdfUrl);
            printwWindow.print();
        }).error(function(data, status, headers, config) {
            alert('Sorry, something went wrong')
        });
    };
<button ng-click="printPdf()" type="button" class="btn btn-primary">Print PDF</button>

With this simple sample code snippet, you can easily download & print pdf by using angularJS.

Categories
AngularJS Code Area

How to Validate Password and Confirm Password in AngularJS

Password and confirm password validation is very common and vital piece of all sort of application. We mostly use it when we are working in signup or password changes page. Here I have written this article to describe AngularJS validation. I will not cover all validation rules in AngularJS, but I will only focus on how to validate password and confirm Password in AngularJS. Let’s see.

How to Validate Password  and Confirm Password in AngularJS
How to Validate Password and Confirm Password in AngularJS

How to Validate Password  and Confirm Password in AngularJS

Here you can I have created an AngularJS directive called matchPassword to validate password and confirm password. This directive is very useful to matching password. In this code snippet I won’t use ngMessage for showing the validation errors (e.g. password not matching error), but It will also working fine with ngMessage.

Thanks for your reading, and please let me know through comments if I missing anything.

Categories
AngularJS Java Script Programming

Remove ngOptions Elements in AngularJS

With the passing time, AngularJS is getting popularity day by day. We all know AngularJS is the structured, most powerful and powerful front-end framework. But today I am not going to describe you about the AngularJS. But I am here to describe an easier & effective way to Remove ngOptions elements in AngularJS.

How to Remove ngOptions Elements in AngularJS

AngularJS provides a ng-options directive to display the options of selectlist. Here I use a categories array (array of object) for the selectlist. Every category object has (id, name, and is_active) keys and is_active true means Active category and is_active false means Inactive category.

Now, I want to display two selectlist, one if for active and another one for inactive. To do this I am using filter:{is_active: true} for active category’s selectlist and filter:{is_active: false} for inactive category’s selectlist.

With this filter, you can easily refine options base on your application needed. So developers can fell free to use is and make their code more maintainable and handy.

If you have any advice or query, please fell free to ask me.

Categories
Angular JS AngularJS HTML Tools and Technologies Web Design

What is AngularJS and How to Start

What is AngularJS?

AngularJS is the web application development framework which provides a flexible way to build testable and maintainable front-end applications. Generally, AngularJS javascript MV framework which is developed by google for build dynamic web application. For more details click here.

How to Start?

It’s really easy to start AngularJS. Just need to download AngularJS JavaScript file, and add to your web page with a script tag: You can also add it from remote url (e.g. http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js).  Here is an example code, so you can see how it works.

Explanation of this Code:

Here I will use 3 types of directives of AngularJS  which are:

ng-app:  This directive will define the angular application, That means this ng-app directive is for initializing the Angular into the page.

ng-model: This directive binds/takes the value from HTML controls (input, select, text area) to application data.

ng-bind: This directive  display the application data to the HTML view.

You can see ng-app directive is declared into the body tag that means Angular  is initialized among whole web page.  and the ng-model directive is declared three times called (name, title, and comment) and which was binds by {{name}}, {{title}}, {{comment}}
{{name}} bind for ng-model="name",
{{title}} bind for ng-model="title",
{{comment}} bind for ng-model="comment"

Output

What is AngularJS and How to Start
What is AngularJS and How to Start

Hope you can learn the basic concept of AngularJS from this article. Thanks!!!

Categories
AngularJS Code Area Java Script

Avoid Curly Braces Conflict in Twig and AngularJS

When you will try to implement AngularJS in Twig Templete Engine,  then you will get a problem with curly braces conflict. To avoid this problem you can override the curly braces ({{}}) for AngularJS, with your custom configuration. It is really easy to override the configuration of angularJS. Here is the sample code snipped to override the configuration.

 

Now you can use (()) instead of {{}}. You can also set anything you want in

$interpolateProvider.startSymbol(‘CUSTOM_SYMBOL);
$interpolateProvider.endSymbol(‘CUSTOM_SYMBOL);
Just replace the “CUSTOM_SYMBOL” with you favorite symbol and then access with that symbol. Hope this tutorial is helpful to you for Avoid Curly Braces Conflict in Twig and AngularJS