AngularJS

Slugify filter

To make strings hyphen separated and url friendly

app.filter('slugify', function () {
    return function (input) {
        if (!input)
            return;

        // make lower case and trim
        var slug = input.toLowerCase().trim();

        // replace invalid chars with spaces
        slug = slug.replace(/[^a-z0-9\s-]/g, '');

        // replace multiple spaces or hyphens with a single hyphen
        slug = slug.replace(/[\s-]+/g, '-');

        return slug;
    };
});

 

Equal height directive to set child elements to the same height

app.directive('equalHeight', function ($timeout) {
    return {
        link: function (scope, element, attr) {
            // wrap in $timeout to wait for element to render
            $timeout(function () {
                // find tallest child element
                var tallest = 0;
                element.children().each(function (index, child) {
                    if ($(child).height() > tallest) {
                        tallest = $(child).height();
                    }
                });

                // set all children to height of tallest child
                element.children().height(tallest);
            });
        }
    }
});

 

Autofocus directive to focus on an element after if has been rendered

app.directive('autoFocus', function () {
    return {
        link: {
            post: function (scope, element, attr) {
                // runs after the element been rendered
                element.focus();
            }
        }
    };
});

 

NodeJS / ExpressJS Routes to prevent 404 error after page refresh in html5mode

var express = require('express');
var path = require('path');
var router = express.Router();

// serve angular front end files from root path
router.use('/', express.static('app', { redirect: false }));

// rewrite virtual urls to angular app to enable refreshing of internal pages
router.get('*', function (req, res, next) {
    res.sendFile(path.resolve('app/index.html'));
});

module.exports = router;

 

IIS URL Rewrite Rule to prevent 404 error after page refresh in html5mode

For angular running under IIS on Windows

<rewrite>
  <rules>
    <rule name="AngularJS" stopProcessing="true">
      <match url=".*" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Rewrite" url="/" />
    </rule>
  </rules>
</rewrite>

 

Clear querystring with $location service

use $location.url([path]) instead of $location.path([path])


 

Filter array to exclude objects based on property value

var users = $filter('filter')(users, { Role: '!' + Role.Admin });

 

ngRepeat with break tag (<br />) separator/delimiter

<span ng-repeat="item in items">
    <a href="#/item.Id">{{item.Name}}</a>
    <br ng-if="!$last" />
</span>

 

Add a custom HTTP Header to all requests

$http.defaults.headers.common['My-Custom-Header'] = 'someValue';

 

Auto-logout if any unauthorised web api request is made

app.config(['$provide', '$httpProvider', function ($provide, $httpProvider) {

    $provide.factory('unauthorisedInterceptor', ['$q', function ($q) {
        return {
            'responseError': function (rejection) {
                if (rejection.status === 401) {
                    window.location.href = '/#/login';
                }

                return $q.reject(rejection);
            }
        };
    }]);

    $httpProvider.interceptors.push('unauthorisedInterceptor');
}])

 

Supported by