Wednesday 11 November 2015

php get the last row with MySQL

If you want the last 10 then just change ASC to DESC

SELECT * 
FROM 
chat 
WHERE 
(userID=$session AND toID=$friendID) 
OR 
(userID=$friendID AND toID=$session) 
ORDER BY id 
DESC
LIMIT 10
SELECT * FROM chat WHERE (userID=$session AND toID=$friendID) OR (userID=$friendID AND toID=$session) ORDER BY id DESC LIMIT 10

Sunday 27 September 2015

A Simple HTML Login page using JavaScript with count

Enter Username : test
Enter Password : test
ENTER USER NAME
ENTER PASSWORD



code here :

 <script type = "text/javascript">

// Note: Like all Javascript password scripts, this is hopelessly insecure as the user can see
//the valid usernames/passwords and the redirect url simply with View Source.
// And the user can obtain another three tries simply by refreshing the page.
//So do not use for anything serious!

var count = 2;
function validate() {
var un = document.myform.username.value;
var pw = document.myform.pword.value;
var valid = false;

var unArray = ["test", "test1"];  // as many as you like - no comma after final entry
var pwArray = ["test", "test1"];  // the corresponding passwords;

for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
break;
}
}

if (valid) {
alert ("Login was successful");
window.location = "view.php";
return false;
}

var t = " tries";
if (count == 1) {t = " try"}

if (count >= 1) {
alert ("Invalid username and/or password.  You have " + count + t + " left.");
document.myform.username.value = "";
document.myform.pword.value = "";
setTimeout("document.myform.username.focus()", 25);
setTimeout("document.myform.username.select()", 25);
count --;
}

else {
alert ("Still incorrect! You have no more tries left!");
document.myform.username.value = "No more tries allowed!";
document.myform.pword.value = "";
document.myform.username.disabled = true;
document.myform.pword.disabled = true;
return false;
}

}

</script>
<p>Enter Username : test </p>
<p>Enter Password : test </p>
<form name = "myform">
<p>ENTER USER NAME <input type="text" name="username"> </p>
<p>ENTER PASSWORD <input type="password" name="pword">
<p><input type="button" value="Check In" name="Submit" onclick= "validate()"></p>

</form><br/><br/>

Thursday 13 August 2015

Tab example with pure javascript to show and hide tab content

Example on show hide button pure javascript



example


<!DOCTYPE html>
<html>

<head>
<meta charset='UTF-8'>
<title>example</title>

 <style type="text/css">
 #page-wrap { width: 100%; background: #ccc; }
.breadcrumbs { margin: 0; padding: 0; }
.breadcrumbs li { float: left; list-style: none; margin: 5px 10px; padding:10px; background-color: #2396D0; }
.breadcrumbs li a { text-decoration: none; color: white; }
.showhidediv { padding: 0; background: #2396D0; width: 100%;  }
.showhidedivC { padding: 10px 0; }
 </style>

</head>

<body>


<div id="page-wrap">


<div class="">
<ul class="breadcrumbs">

<li class="nobg"><input type="button" value="1 button" onclick="show('div1')"/></li>
<li class="nobg"><input type="button" value="2 button" onclick="show('div2')"/></li>
<li class="nobg"><input type="button" value="3 button" onclick="show('div3')"/></li>
<li class="nobg"><input type="button" value="4 button" onclick="show('div4')"/></li>

</ul>
</div>
<div style="clear:both;"></div>

<div class="showhidediv">

<div class="showhidedivC" id="div1" style="display:none;">
111111111111
<input type="button" value="button1" />
<input type="button" value="button1" />
<input type="button" value="button1" />
<input type="button" value="button1" />
<input type="button" value="button1" />
<input type="button" value="button1" />
</div>
<div class="showhidedivC" id="div2" style="display:none;">
22222222222222222
<input type="button" value="button1" />
<input type="button" value="button1" />
<input type="button" value="button1" />
<input type="button" value="button1" />
<input type="button" value="button1" />
<input type="button" value="button1" />
</div>
<div class="showhidedivC" id="div3" style="display:none;">
333333333333333
<input type="button" value="button1" />
<input type="button" value="button1" />
<input type="button" value="button1" />
<input type="button" value="button1" />
<input type="button" value="button1" />
<input type="button" value="button1" />
</div>
<div class="showhidedivC" id="div4" style="display:none;">
44444444444444444444
<input type="button" value="button1" />
<input type="button" value="button1" />
<input type="button" value="button1" />
<input type="button" value="button1" />
<input type="button" value="button1" />
<input type="button" value="button1" />
</div>


</div>

</div>


<script>
for (i=1; i<5;i++){

    var currentDiv = document.getElementById("div"+i);
 
    function show(divID) {
        var div = document.getElementById(divID);

        currentDiv.style.display = "none";
        div.style.display = "block";

        currentDiv = div;
    }
    i++;

    }

</script>

</body>

</html>


Tuesday 11 August 2015

AngularJS User Registration and Login Example

AngularJS User Registration and Login Example Reference took from http://jasonwatmore.com/post/2015/03/10/AngularJS-User-Registration-and-Login-Example.aspx Plunker link example : http://embed.plnkr.co/Mvrte4/preview AngularJS User Registration and Login Example Building on from a previous article I posted on how to implement Basic HTTP Authentication with AngularJS, in this post I've extended that example to include a simple user registration form. The project is available on GitHub at https://github.com/cornflourblue/angular-registration-login-example The example uses HTML5 local storage for storing the users so I could show it working without a back end, however the project also contains a user service built to interact with a RESTful web service. To switch from local storage to the web service implementation just update which script is embedded in the index.html file, note that for this to work you also need to create the RESTful web service for managing users :) AngularJS Project Structure I've based a lot of the project and code structure on recommendations from John Papa's style guide with my own tweaks here and there, for example I've placed application config and routes within the app.js file rather than separate files because there isn't much code in either section, these could be split out later if the sections grow. I'm also trying out placing application services and content in folders prefixed with 'app-' to prevent having a name clash if I need to add a section to my app called 'services' or 'content', it also has the added benefit of grouping all the 'non-gui' code together at the top of the folders. Here's what the project structure looks like: app-content app.css app-services authentication.service.js flash.service.js user.service.js user.service.local-storage.js home home.controller.js home.view.html login login.controller.js login.view.html register register.controller.js register.view.html app.js index.html Below I've included brief descriptions of the main files that have to do with user registration and authentication, all the files are available at the github project linked at the top of the post. AngularJS Authentication Service Back to top The authentication service contains methods for authenticating a user, setting credentials and clearing credentials from the HTTP "Authorization" headers used by the AngularJS $http service, so effectively logging in and out. The example uses dummy authentication in order to show the example working on plunker without a back end, but real authentication can be setup by following the comments in the Login function. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 (function () { 'use strict'; angular .module('app') .factory('AuthenticationService', AuthenticationService); AuthenticationService.$inject = ['$http', '$cookieStore', '$rootScope', '$timeout', 'UserService']; function AuthenticationService($http, $cookieStore, $rootScope, $timeout, UserService) { var service = {}; service.Login = Login; service.SetCredentials = SetCredentials; service.ClearCredentials = ClearCredentials; return service; function Login(username, password, callback) { /* Dummy authentication for testing, uses $timeout to simulate api call ----------------------------------------------*/ $timeout(function () { var response; UserService.GetByUsername(username) .then(function (user) { if (user !== null && user.password === password) { response = { success: true }; } else { response = { success: false, message: 'Username or password is incorrect' }; } callback(response); }); }, 1000); /* Use this for real authentication ----------------------------------------------*/ //$http.post('/api/authenticate', { username: username, password: password }) // .success(function (response) { // callback(response); // }); } function SetCredentials(username, password) { var authdata = Base64.encode(username + ':' + password); $rootScope.globals = { currentUser: { username: username, authdata: authdata } }; $http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; // jshint ignore:line $cookieStore.put('globals', $rootScope.globals); } function ClearCredentials() { $rootScope.globals = {}; $cookieStore.remove('globals'); $http.defaults.headers.common.Authorization = 'Basic '; } } // Base64 encoding service used by AuthenticationService var Base64 = { keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', encode: function (input) { var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; do { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + this.keyStr.charAt(enc1) + this.keyStr.charAt(enc2) + this.keyStr.charAt(enc3) + this.keyStr.charAt(enc4); chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return output; }, decode: function (input) { var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; // remove all characters that are not A-Z, a-z, 0-9, +, /, or = var base64test = /[^A-Za-z0-9\+\/\=]/g; if (base64test.exec(input)) { window.alert("There were invalid base64 characters in the input text.\n" + "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" + "Expect errors in decoding."); } input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); do { enc1 = this.keyStr.indexOf(input.charAt(i++)); enc2 = this.keyStr.indexOf(input.charAt(i++)); enc3 = this.keyStr.indexOf(input.charAt(i++)); enc4 = this.keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return output; } }; })(); AngularJS User Service Back to top A user service designed to interact with a RESTful web service to manage users within the system. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 (function () { 'use strict'; angular .module('app') .factory('UserService', UserService); UserService.$inject = ['$http']; function UserService($http) { var service = {}; service.GetAll = GetAll; service.GetById = GetById; service.GetByUsername = GetByUsername; service.Create = Create; service.Update = Update; service.Delete = Delete; return service; function GetAll() { return $http.get('/api/users').then(handleSuccess, handleError('Error getting all users')); } function GetById(id) { return $http.get('/api/users/' + id).then(handleSuccess, handleError('Error getting user by id')); } function GetByUsername(username) { return $http.get('/api/users/' + username).then(handleSuccess, handleError('Error getting user by username')); } function Create(user) { return $http.post('/api/users', user).then(handleSuccess, handleError('Error creating user')); } function Update(user) { return $http.put('/api/users/' + user.id, user).then(handleSuccess, handleError('Error updating user')); } function Delete(id) { return $http.delete('/api/users/' + id).then(handleSuccess, handleError('Error deleting user')); } // private functions function handleSuccess(data) { return data; } function handleError(error) { return function () { return { success: false, message: error }; }; } } })(); AngularJS Fake User Service (Local Storage) Back to top A fake user service that stores users in local storage in the browser, it mimics the behaviour of the real user service by returning promises and using $timeout. When creating a user, the service checks if a username is already taken and returns an error message, in a real implementation using a web service this action would be performed on the server. To switch between using this fake user service and the real one above update the scripts section at the bottom of the index.html file. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 (function () { 'use strict'; angular .module('app') .factory('UserService', UserService); UserService.$inject = ['$timeout', '$filter', '$q']; function UserService($timeout, $filter, $q) { var service = {}; service.GetAll = GetAll; service.GetById = GetById; service.GetByUsername = GetByUsername; service.Create = Create; service.Update = Update; service.Delete = Delete; return service; function GetAll() { var deferred = $q.defer(); deferred.resolve(getUsers()); return deferred.promise; } function GetById(id) { var deferred = $q.defer(); var filtered = $filter('filter')(getUsers(), { id: id }); var user = filtered.length ? filtered[0] : null; deferred.resolve(user); return deferred.promise; } function GetByUsername(username) { var deferred = $q.defer(); var filtered = $filter('filter')(getUsers(), { username: username }); var user = filtered.length ? filtered[0] : null; deferred.resolve(user); return deferred.promise; } function Create(user) { var deferred = $q.defer(); // simulate api call with $timeout $timeout(function () { GetByUsername(user.username) .then(function (duplicateUser) { if (duplicateUser !== null) { deferred.resolve({ success: false, message: 'Username "' + user.username + '" is already taken' }); } else { var users = getUsers(); // assign id var lastUser = users[users.length - 1] || { id: 0 }; user.id = lastUser.id + 1; // save to local storage users.push(user); setUsers(users); deferred.resolve({ success: true }); } }); }, 1000); return deferred.promise; } function Update(user) { var deferred = $q.defer(); var users = getUsers(); for (var i = 0; i < users.length; i++) { if (users[i].id === user.id) { users[i] = user; break; } } setUsers(users); deferred.resolve(); return deferred.promise; } function Delete(id) { var deferred = $q.defer(); var users = getUsers(); for (var i = 0; i < users.length; i++) { var user = users[i]; if (user.id === id) { users.splice(i, 1); break; } } setUsers(users); deferred.resolve(); return deferred.promise; } // private functions function getUsers() { if(!localStorage.users){ localStorage.users = JSON.stringify([]); } return JSON.parse(localStorage.users); } function setUsers(users) { localStorage.users = JSON.stringify(users); } } })(); AngularJS Login Controller Back to top The Login Controller clears the user credentials on load which logs the user out if they were logged in. The login function exposed by the controller calls the Authentication Service to authenticate the username and password entered into the view. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 (function () { 'use strict'; angular .module('app') .controller('LoginController', LoginController); LoginController.$inject = ['$location', 'AuthenticationService', 'FlashService']; function LoginController($location, AuthenticationService, FlashService) { var vm = this; vm.login = login; (function initController() { // reset login status AuthenticationService.ClearCredentials(); })(); function login() { vm.dataLoading = true; AuthenticationService.Login(vm.username, vm.password, function (response) { if (response.success) { AuthenticationService.SetCredentials(vm.username, vm.password); $location.path('/'); } else { FlashService.Error(response.message); vm.dataLoading = false; } }); }; } })(); AngularJS Login View Back to top The Login View contains a small form with the usual fields for username and password, and some validation directives and messages. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

Login

{{vm.error}}
Username is required
Password is required
Register
AngularJS Register Controller Back to top The Register Controller exposes a single register method which is called from the register view when the form is submitted. The register method then calls the UserService.Create method to save the new user. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 (function () { 'use strict'; angular .module('app') .controller('RegisterController', RegisterController); RegisterController.$inject = ['UserService', '$location', '$rootScope', 'FlashService']; function RegisterController(UserService, $location, $rootScope, FlashService) { var vm = this; vm.register = register; function register() { vm.dataLoading = true; UserService.Create(vm.user) .then(function (response) { if (response.success) { FlashService.Success('Registration successful', true); $location.path('/login'); } else { FlashService.Error(response.message); vm.dataLoading = false; } }); } } })(); AngularJS Register View Back to top The Register View contains just a few fields for user data and some directives for validation. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

Register

{{vm.error}}
First name is required
Last name is required
Username is required
Password is required
Cancel
AngularJS App.js Back to top The part of this file related to authentication is in the run function, when the app starts it checks if there's a cookie containing user credentials meaning the user has already logged in, this is to keep the user logged in after a page refresh. On each location change there's a check to verify that the user is logged in if trying to access a restricted page, if not they're redirected to the login page. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 (function () { 'use strict'; angular .module('app', ['ngRoute', 'ngCookies']) .config(config) .run(run); config.$inject = ['$routeProvider', '$locationProvider']; function config($routeProvider, $locationProvider) { $routeProvider .when('/', { controller: 'HomeController', templateUrl: 'home/home.view.html', controllerAs: 'vm' }) .when('/login', { controller: 'LoginController', templateUrl: 'login/login.view.html', controllerAs: 'vm' }) .when('/register', { controller: 'RegisterController', templateUrl: 'register/register.view.html', controllerAs: 'vm' }) .otherwise({ redirectTo: '/login' }); } run.$inject = ['$rootScope', '$location', '$cookieStore', '$http']; function run($rootScope, $location, $cookieStore, $http) { // keep user logged in after page refresh $rootScope.globals = $cookieStore.get('globals') || {}; if ($rootScope.globals.currentUser) { $http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata; // jshint ignore:line } $rootScope.$on('$locationChangeStart', function (event, next, current) { // redirect to login page if not logged in and trying to access a restricted page var restrictedPage = $.inArray($location.path(), ['/login', '/register']) === -1; var loggedIn = $rootScope.globals.currentUser; if (restrictedPage && !loggedIn) { $location.path('/login'); } }); } })();

Saturday 20 June 2015

Allow only numbers to be typed into a text box angularjs

There is an input number directive which I belive can do just what you want.
<input type="number"
   ng-model="{string}"
   [name="{string}"]
   [min="{string}"]
   [max="{string}"]
   [required]
   [ng-required="{string}"]
   [ng-minlength="{number}"]
   [ng-maxlength="{number}"]
   [ng-pattern="{string}"]
   [ng-change="{string}"]>
 <input type="text" name="number" numbs-only>
.directive('numbsonly', function () {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function (scope, element, attr, ctrl) {
        function inputValue(val) {
          if (val) {
            var digits = val.replace(/[^0-9.]/g, '');

            if (digits !== val) {
              ctrl.$setViewValue(digits);
              ctrl.$render();
            }
            return parseFloat(digits);
          }
          return undefined;
        }            
        ctrl.$parsers.push(inputValue);
      }
    };
 });
You could easily use the ng-pattern.
ng-pattern="/^[1-9][0-9]{0,2}(?:,?[0-9]{3}){0,3}(?:\.[0-9]{1,2})?$/"

Friday 12 June 2015

Add Routing in AngularJS



AngularJS routes enable you to create different URLs for different content in your application. Having different URLs for different content enables the user to bookmark URLs to specific content, and send those URLs to friends etc. In AngularJS each such bookmarkable URL is called a route.
AngularJS routes enables you to show different content depending on what route is chosen. A route is specified in the URL after the # sign. Thus, the following URL's all point to the same AngularJS application, but each point to different routes:
    http://myangularjsapp.com/index.html#books
    http://myangularjsapp.com/index.html#albums
    http://myangularjsapp.com/index.html#games
    http://myangularjsapp.com/index.html#apps
When the browser loads these links, the same AngularJS application will be loaded (located athttp://myangularjsapp.com/index.html), but AngularJS will look at the route (the part of the URL after the #) and decide what HTML template to show.
At this point it may sound a little abstract, so let us look at a fully working AngularJS route example:
<!DOCTYPE html>
<html lang="en">
<head>
    <title>AngularJS Routes example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
</head>

<body ng-app="sampleApp">

<a href="#/route1/abcd">Route 1 + param</a><br/>
<a href="#/route2/1234">Route 2 + param</a><br/>


<div ng-view></div>

<script>
    var module = angular.module("sampleApp", ['ngRoute']);

    module.config(['$routeProvider',
        function($routeProvider) {
            $routeProvider.
                    when('/route1/:param', {
                        templateUrl: 'angular-route-template-1.jsp',
                        controller: 'RouteController'
                    }).
                    when('/route2/:param', {
                        templateUrl: 'angular-route-template-2.jsp',
                        controller: 'RouteController'
                    }).
                    otherwise({
                        redirectTo: '/'
                    });
        }]);

    module.controller("RouteController", function($scope, $routeParams) {
        $scope.param = $routeParams.param;
    })
</script>



</body>
</html> 
reference taken from http://tutorials.jenkov.com/angularjs/routes.html

Wednesday 15 April 2015

Custom font not working in ie

In Internet Explorer 8 and earlier, the URL must point to an Embedded OpenType (EOT) file (.eot or .ote format). No other font formats are supported.

Below css will work in all browsers

@font-face {
    font-family: "customfontname";
    src: url('customfontname.eot?#iefix') format('embedded-opentype'), 
         url('customfontname.woff') format('woff'), 
         url('customfontname.ttf')  format('truetype'),
         url('customfontname.svg#customfontname') format('svg'),    
         url("../customfontname.woff2") format("woff2");
    font-weight: normal;
    font-style: normal;
}

Tuesday 7 April 2015

Custom Directive in AngularJS

Custom Directive Introduction

AngularJS directives are what controls the rendering of the HTML inside an AngularJS application. Examples of directives are the interpolation directive ( {{ }} ), the ng-repeat directive and ng-if directive.
It is possible to implement your own directives too. This is what AngularJS refers to as "teaching HTML new tricks". This text will show you how to do that.

Directive Types

You can implement the following types of directives:
  • Element directives
  • Attribute directives
  • CSS class directives
  • Comment directives
Of these, AngularJS recommends that you try to use element and attribute directives, and leave the CSS class and comment directives (unless absolutely necessary).
The type of a directive determines how the directive is activated. An element directive is activated when AngularJS finds a matching HTML element in the HTML template. An attribute directive is activated when AngularJS finds a matching HTML element attribute. A CSS class directive is activated when AngularJS finds a matching CSS Class. And, a comment directive is activated when AngularJS finds a matching HTML comment.

A Basic Directive

You register a directive with a module. Here is an example of how that looks:
myapp = angular.module("myapp", []);

myapp.directive('div', function() {
    var directive = {};

    directive.restrict = 'E'; /* restrict this directive to elements */

    directive.template = "My first directive: {{textToInsert}}";

    return directive;
});
Notice the call to the directive() function on the module. When you call this function you can register a new directive. The first parameter to the directive() function call is the name of the directive to register. This name is what you use in your HTML templates when you want to activate the directive. In this example I have used the name 'div' which means that the directive is activated every time an HTML element named div is found in the HTML template.
The second parameter passed to the directive function is a factory function. This function should return a directive definition when invoked. AngularJS will invoke this function to obtain a JavaScript object which contains the definition of the directive. If you look inside the function in the above example you will see that it does indeed return a JavaScript object.
The JavaScript object returned from the factory function has two properties: A restrict field and a templatefield.
The restrict field is used to set if the directive should be activated by a matching HTML element, or an element attribute. By setting restrict to E you specify that only HTML elements named div should activate the directive. By setting restrict to A you specify that only HTML attributes named div should activate the directive. You can also use a value of AE which will match both HTML element names and attribute names.
The template field is an HTML template that will replace the content of the matched div element. It will work as if the content of the matched div element had not been there, and instead this HTML template had been located in the same place.
Imagine that your HTML page has this HTML:
<div ng-controller="MyController" >
    <div>This div will be replaced</div>
</div>
Then the added directive would be activated when AngularJS finds the inner div element. Instead of this divelement, this HTML will be inserted:
My first directive: {{textToInsert}}
As you can see, this HTML contains an interpolation directive ({{textToInsert}}). AngularJS will interpret this HTML again, so that the interpolation directive actually works. The value of the $scope.textToInsertproperty will be inserted at this point in the HTML.

The template and templateUrl Properties

The easiest way to create your own directives is as shown in the example above. Your directive is intended to generate HTML, and you put that HTML inside the template attribute of the directive definition object. Here is the directive definition repeated from earlier, with the template string marked in bold:
myapp = angular.module("myapp", []);

myapp.directive('div', function() {
    var directive = {};

    directive.restrict = 'E'; /* restrict this directive to elements */
    directive.template = "My first directive: {{textToInsert}}";

    return directive;
});
In case that HTML template grows big, it is gets hard to write and maintain the HTML inside a JavaScript string. You can then put the HTML into its own file and have AngularJS load it from that file. You do so by putting the URL of the HTML template file into the templateUrl property of the directive definition object. Here is an example:
myapp = angular.module("myapp", []);

myapp.directive('div', function() {
    var directive = {};

    directive.restrict = 'E'; /* restrict this directive to elements */
    directive.templateUrl = "/myapp/html-templates/div-template.html";

    return directive;
});
AngularJS will now load the HTML template from the URL set in the templateUrl property.
Using the separate HTML template file and the templateUrl property is especially useful when you create more specialized directives, like a directives showing user info. Here is an example:
myapp = angular.module("myapp", []);

myapp.directive('userinfo', function() {
    var directive = {};

    directive.restrict = 'E'; /* restrict this directive to elements */
    directive.templateUrl = "/myapp/html-templates/userinfo-template.html";

    return directive;
});
This example creates a directive that is activated whenever AngularJS finds a <userinfo> element. AngularJS loads the HTML template found at /myapp/html-templates/userinfo-template.html, and interprets that as if it had been located inside the parent HTML file from the beginning.

Isolating the $scope From the Directive

In the example above the userinfo directive was bound hard to the $scope variable because the HTML template referenced the textToInsert property directly. Referencing $scope variables directly makes it hard to reuse the directive more than once within the same controller, since the $scope variables typically have the same values everywhere inside the same controller. For instance, if you wanted to have this HTML in your page:
<userinfo></userinfo>
<userinfo></userinfo>
Then the two <userinfo> elements would be replaced by the same HTML template, which is bound to the same $scope variable. The result would be that the two <userinfo> elements would be replaced by the exact same HTML code.
To be able to bind the two <userinfo> elements to different values in the $scope object, you need to bind the HTML template to an isolate scope.
An isolate scope is a separate scope object tied to the directive. Here is how you define it in the directive definition object:
myapp.directive('userinfo', function() {
    var directive = {};

    directive.restrict = 'E';

    directive.template = "User : {{user.firstName}} {{user.lastName}}";

    directive.scope = {
        user : "=user"
    }

    return directive;
})
Notice how the HTML template has two interpolation directives bound to {{user.firstName}} and{{user.lastName}}. Notice the user. part. And notice the directive.scope property. Thedirective.scope property is a JavaScript object which contains a property named user. Thedirective.scope property is the isolate scope object, and the HTML template is now bound to thedirective.scope.user object (via the {{user.firstName}} and {{user.lastName}} interpolation directives).
The directive.scope.user property is set to "=user". That means, that the directive.scope.userproperty is bound to the property in the scope property (not in the isolate scope) with the name passed to theuser attribute of the <userinfo> element. It sounds confusing, so look at this HTML example:
<userinfo user="jakob"></userinfo>
<userinfo user="john"></userinfo>
These two <userinfo> element contain a user attribute. The value of these attributes contain the names of properties in the $scope object which are to be referenced by the isolate scope object's userinfo property.
Here is a full example:
<userinfo user="jakob"></userinfo>
<userinfo user="john"></userinfo>

<script>
myapp.directive('userinfo', function() {
    var directive = {};

    directive.restrict = 'E';

    directive.template = "User : <b>{{user.firstName}}</b> <b>{{user.lastName}}</b>";

    directive.scope = {
        user : "=user"
    }

    return directive;
});

myapp.controller("MyController", function($scope, $http) {
    $scope.jakob = {};
    $scope.jakob.firstName = "Jakob";
    $scope.jakob.lastName  = "Jenkov";

    $scope.john = {};
    $scope.john.firstName = "John";
    $scope.john.lastName  = "Doe";
});

</script>

The compile() and link() Functions

If you need to do something more advanced inside your directive, something that you cannot do with an HTML template, you can use the compile() and link() functions instead.
The compile() and link() functions define how the directive is to modify the HTML that matched the directive.
The compile() function is called once for each occurrence of the directive in the HTML page. The compile()function can then do any one-time configuration needed of the element containing the directive.
The compile() function finishes by returning the link() function. The link() function is called every time the element is to be bound to data in the $scope object.
As mentioned, you add the compile() function to the directive definition object, and the compile() function has to return the link() function when executed. Here is how that looks:
<script>
myapp = angular.module("myapp", []);
myapp.directive('userinfo', function() {
    var directive = {};

    directive.restrict = 'E'; /* restrict this directive to elements */


    directive.compile = function(element, attributes) {
        // do one-time configuration of element.

        var linkFunction = function($scope, element, atttributes) {
            // bind element to data in $scope
        }

        return linkFunction;
    }

    return directive;
});    
</script>    
The compile() function takes two parameters: The element and attributes parameters.
The element parameter is a jqLite wrapped DOM element. AngularJS contains a lite version of jQuery to help you do DOM manipulation, so the element's DOM manipulation methods are the same as you know from jQuery.
The attributes parameter is a JavaScript object containing properties for all the attributes of the DOM element. Thus, to access an attribute named type you would write attributes.type.
The link() function takes three parameters: The $scope parameter, the element parameter and theattributes parameter. The element and attributes parameter is the same as passed to the compile()function. The $scope parameter is the normal scope object, or an isolate scope in case you have specified one in the directive definition object.
The compile() and link() function names are actually confusing. They are inspired by compiler terms. I can see the resemblance, but a compiler parses an input once, and creates an output. A directive configures an HTML element and then updates that HTML subsequently whenever the $scope object changes.
A better name for the compile() function would have been something like create()init() orconfigure(). Something that signals that this function is only called once.
A better name for the link() function would have been something like bind() or render(), which signals that this function is called whenever the directive needs to bind data to it, or to re-render it.
Here is a full example that shows a directive that uses both a compile() and link() function:
<div ng-controller="MyController" >
    <userinfo >This will be replaced</userinfo>
</div>

<script>
    myapp = angular.module("myapp", []);
    myapp.directive('userinfo', function() {
        var directive = {};

        directive.restrict = 'E'; /* restrict this directive to elements */

        directive.compile = function(element, attributes) {
            element.css("border", "1px solid #cccccc");

            var linkFunction = function($scope, element, attributes) {
                element.html("This is the new content: " + $scope.firstName);
                element.css("background-color", "#ffff00");
            }

            return linkFunction;
        }

        return directive;
    })
    myapp.controller("MyController", function($scope, $http) {
        $scope.cssClass = "notificationDiv";

        $scope.firstName = "Jakob";

        $scope.doClick = function() {
            console.log("doClick() called");
        }
    });
</script>    
The compile() function sets a border on the HTML element. This is only executed once because thecompile() function is only executed once.
The link() function replaces the content of the HTML element, and sets the background color to yellow.
There is no particular reason why the border was set in the compile() function, and the background color in the link() function. Both could have been set in the compile() function, or both in the link() function. If set in the compile() function they would only have been set once (which is often what you want). If set in thelink() function they would be set every time the HTML element is bound to data in the $scope object. This might be useful if you needed to set the border and background color differently depending on data in the$scope object.

Setting Only a link() Function

Sometimes you do not need the compile() step for your directive. You only need th link() function. In that case you can set the link() function directly on the directive definition object. Here is the example from before, with only a link function:
<div ng-controller="MyController" >
    <userinfo >This will be replaced</userinfo>
</div>

<script>
    myapp = angular.module("myapp", []);
    myapp.directive('userinfo', function() {
        var directive = {};

        directive.restrict = 'E'; /* restrict this directive to elements */

        directive.link = function($scope, element, attributes) {
                element.html("This is the new content: " + $scope.firstName);
                element.css("background-color", "#ffff00");
        }

        return directive;
    })
    myapp.controller("MyController", function($scope, $http) {
        $scope.cssClass = "notificationDiv";

        $scope.firstName = "Jakob";

        $scope.doClick = function() {
            console.log("doClick() called");
        }
    });
</script>
Notice how the link() function does the same as the link() function returned in the previous example.

Directives Which Wraps Elements Via Transclusion

The examples we have seen so far all set the content of the element matching the directive themselves, either via JavaScript code or an HTML template. But what if you wanted a directive to wrap elements inserted into the directive body by the developer? For instance:
<mytransclude>This is a transcluded directive {{firstName}}</mytransclude>
The directive is marked by the <mytransclude> element. But the content inside it is set by the developer. Thus, this part of the HTML should not be replaced by the directive's HTML template. We actually want that part of the HTML to be processed by AngularJS. This processing is called "transclusion".
In order to make AngularJS process the HTML inside a directive, you have to set the transclude property of the directive definition object to true. You will also have to tell AngularJS what part of the directive's HTML template that is to contain the transcluded HTML. You do so by inserting the ng-transclude attribute (a directive, really) into the HTML element in the HTML template where you want the transcluded HTML inserted.
Here is an AngularJS directive that shows how to use transclusion:
<mytransclude>This is a transcluded directive {{firstName}}</mytransclude>

<script>
    myapp = angular.module("myapp", []);
    myapp.directive('mytransclude', function() {
        var directive = {};

        directive.restrict = 'E'; /* restrict this directive to elements */
        directive.transclude = true;
        directive.template = "<div class='myTransclude' ng-transclude></div>";

        return directive;
    });
    myapp.controller("MyController", function($scope, $http) {
        $scope.firstName = "Jakob";
    });
</script>

Notice the HTML inside the <mytransclude> element. This HTML code contains the interpolation directive{{firstName}}. We want AngularJS to process this HTML for us so that interpolation directive is executed. To achieve that I have set the transclude property to true on the directive definition object. I have also inserted an ng-transclude attribute into the HTML template. This attribute tells AngularJS what element to insert the transcluded HTML into.


reference : http://tutorials.jenkov.com/angularjs/custom-directives.html