<!doctype html>
<html ng-app="myApp">
<head>
    <title>Unique</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="app.js"></script>
    <script src="service.js"></script>
    <script src="directive.js"></script>
    </head>
    <body ng-controller="myCtrl">
        <form name="editForm">
    <input type="email" name="email"
    ng-model="email" 
    unique-id="{key: customer.id, property: 'email'}"
    required /> 
            <span class="errorMessage" ng-show="editForm.email.$dirty && editForm.email.$error.unique">
    Email already in use
</span>
        </form>
    </body>
</html>
angular.module('myApp',[])
.controller('myCtrl',function(){
    
    
    
})
angular.module('myApp')
    .factory('dataService',function($http){
    
    var serviceBase="username.json";
    var dataFactory={};
    
     dataFactory.checkUniqueValue = function (id, property, value) {
            if (!id) id = 0;
            return $http.get(serviceBase)
                .then(
                function (results) {
                    console.log(results.data[0].property);
                    return results.data[0].property;
                });
        };
        console.log(dataFactory);
        return dataFactory;

});
angular.module('myApp')
    .directive('uniqueId', ['dataService', function (dataService) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            element.bind('blur', function (e) {
               
                if (!ngModel || !element.val()) return;
                var keyProperty = scope.$eval(attrs.uniqueId);
                console.log(keyProperty)
                var currentValue = element.val();
                
                dataService.checkUniqueValue(keyProperty.key, keyProperty.property, currentValue)
                    .then(function (unique) {
                    
                        console.log(unique)
                        //Ensure value that being checked hasn't changed
                        //since the Ajax call was made
                        if (currentValue == element.val()) {
                            console.log(ngModel.$setValidity('unique', unique));        
                            ngModel.$setValidity('unique', unique);
                        }
                    }, function () {
                        //Probably want a more robust way to handle an error
                        //For this demo we'll set unique to true though
                        ngModel.$setValidity('unique', true);
                    });
            });
        }
    }
}]);
[
    {
        "key":"0",
        "property":"nitesh@gmail.com"
    }
]