Tuesday 12 April 2016

Simple custom directive in AngularJs Code example

I tried to much, but what i feel is practice make us perfect. It was tough for me to understand custom directive in AngularJs, i didn't found anywhere something cool like this which created myself. Given code snippet might be your favorite.



<html>
<head>
    <title>Simple custom directive in angularJs with demo</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
  </head>
<body>
    <div ng-app="myapp">
        <form name="myForm" ng-submit="doSomething()">
            <input type="text" name="name" ng-model="username" customlength />
            <span ng-show="myForm.name.$error.isvalidlength">length must be greater then 3. </span>
            <span ng-show="!myForm.name.$error.isvalidlength">Valid length.</span>
            <br/>
            <button type="submit" ng-disabled="myForm.$invalid">Submit</button>
        </form>
    </div>


    <script>
        var app = angular.module("myapp", []);
        //creating custom directive to check string length
        app.directive('customlength', function () {
            return {
                require: 'ngModel', // default AngularJS's own NgModelController for custom directive, we could use our own controller here
                link: function (scope, element, attrs, ctrl) {
                    scope.$watch(function () { //element.on('keyup', function () {
                        console.log(element.val()); // to check event is calling properly or not
                        var match = false;
                        if (element.val().length >= 3) {
                            match = true;
                        }
                        ctrl.$setValidity('isvalidlength', match);
                    });
                }
            }
        });

    </script>
</body>
</html>