Showing posts with label angularjs. Show all posts
Showing posts with label angularjs. Show all posts

Monday, October 24, 2022

Laravel Blade @include .html files | Laravel Blade Highlight Change Tags when use AngularJS along with Laravel

I am going to use AngularJS along with Laravel, and I wanted to change Laravel tags to [[ ]], it can achived by below codes:

Blade::setContentTags('[[', ']]'); // for variables and all things Blade

Blade::setEscapedContentTags('[[[', ']]]'); // for escaped data
But my solution is to have Angular and Blade works very simple, I create a another xxx.php every time instead of xxx.blade.php. I need some Angular and name this partial just '.php' and not '.blade.php'.

Lets say I have a user create form named "create.blade.php" inside "views/user" directory using below content:

@extends('layouts.user')
@section('content')
    <form>
        <h2>Create User</h2>
        @include('user.createBody');
    </form>
@endsection

Now I will create an php file named "createBody.php" inside "views/user" directory and put some html there:

<div class="row">
    <h1>User Name={{userName}}</h1>
    <div class="col-lg-4 col-sm-6">
        <label>Name</label>
        <input type="text" class="form-control" ng-model="userName">
    </div>
    <div class="col-lg-4 col-sm-6">
        <label>ID</label>
        <input type="text" class="form-control">
    </div>
</div>

So here we can use {{ }} tags both in Laravel and AngularJS

Thursday, May 18, 2017

AngularJS How to call controller function from outside of controller component

Its not a good practice to call AngularJS function from outside of its scope. But sometimes we need it badly. So there is a way around to do this easily.

You should note that scopes are initialized after the page is fully loaded, so calling methods from outside of scope should always be done after the page is loaded. Else you will not get to the scope at all. Below is a small code snippet to how you can achieve this easily:

var targetID = document.getElementById("AngularController");
angular.element(targetID).scope().init("Outside Controller");

Where "init" is function named in your controller as below:

var app = angular.module("myApp", []);
app.controller("AngularController", function($scope, $window) {
    $scope.init = function(res) {
        console.log("INIT INVOKED=" + res);
    };

    $scope.init("Controller Itself");
});








You can download full example from the link.


Saturday, January 14, 2017

Implement Redirect Interceptor For All Http Call - Angular JS

Download resources from here


<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript" src="angular-resource.js"></script>

<div data-ng-app="myApp" data-ng-controller="MyCtrl">[[dataFromAngularJS]]</div>

<script type="text/javascript">
    var app = angular.module('myApp', ['ngResource'], function ($interpolateProvider) {
        $interpolateProvider.startSymbol('[[');
        $interpolateProvider.endSymbol(']]');
    });
    app.config(['$httpProvider', '$controllerProvider', function ($httpProvider, $controllerProvider, $window) {
        $httpProvider.interceptors.push('redirectInterceptor');
    }])
    .run(function ($rootScope, $window) {
        console.log("MY_APP START RUNNING");
        $rootScope.baseUrl = "/";
    })
    .factory('redirectInterceptor', function ($q, $location, $window, $rootScope) {
        return {
            response: function (response) {
                console.log("GOT DATA VIA AJAX CALL");
                console.log(response);
                return response;
            },
            responseError: function(response) {
                console.log("GOT ERROR VIA AJAX CALL");
                console.log(response);
                response.data = "ERROR";
                return $q.reject(response);
            }
        }
    });

    app.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {
        $scope.dataFromAngularJS = "Data From Angular JS";

        $http.get('data.html').
        success(function(response, status, headers, config) {
            $scope.dataFromAngularJS = "Success=" + response;
        }).
        error(function(response, status, headers, config) {
            $scope.dataFromAngularJS = "Error=" + response;
        });
    }]);
</script>

Sunday, December 18, 2016

Start watch form field change listener - Angular JS

Download full example code from here


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Start watch form field change listener - Angular JS</title>
    <script type="text/javascript" src="jquery-min.js"></script>
    <script type="text/javascript" src="angular.js"></script>
</head>
<body>

<div data-ng-app="myApp" data-ng-controller="MyCtrl">
    <form name="myForm">
        <table>
            <tr>
                <td>Name</td>
                <td><input type="text" data-ng-model="dataObject.Name"></td>
            </tr>
            <tr>
                <td>Group</td>
                <td>
                    <select data-ng-model="dataObject.Group">
                        <option value="GROUP_1">Group 1</option>
                        <option value="GROUP_2">Group 2</option>
                        <option value="GROUP_3">Group 3</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Radio</td>
                <td>
                    <input type="radio" data-ng-model="dataObject.Radio" value="1"/>
                    <input type="radio" data-ng-model="dataObject.Radio" value="2"/>
                </td>
            </tr>
            <tr>
                <td>Checkbox</td>
                <td>
                    <label ng-repeat="Option in Options">
                        <input type="checkbox" name="OptionValues[]" value="{{Option.Id}}" ng-model="Option.Checked">
                        {{Option.Name}}
                    </label>
                </td>
            </tr>
            <tr>
                <td>Type</td>
                <td><input type="text" data-ng-model="Type"></td>
            </tr>
        </table>
        <div class="log"></div>
    </form>
</div>

<script type="text/javascript">
    var myApp = angular.module('myApp', []), log = $(".log");

    myApp.controller('MyCtrl', ['$scope', function($scope) {
        /* Start watching Object */
        $scope.dataObject = {Name: "", Group: "GROUP_1", Radio: "1"};
        $scope.$watch('dataObject', function(newVal, oldVal) {
            $scope.printChangedField(newVal, oldVal);
        }, true);

        $scope.printChangedField = function(newVal, oldVal) {
            Object.keys(oldVal).forEach(function (key) {
                if(newVal[key] != oldVal[key]) {
                    log.prepend('Field \"' + key + '\" Changed From=\"' + oldVal[key] + '\" To=\"' + newVal[key] + '\"<BR>');
                }
            });
        };

        /* Start watching checkboxes */
        $scope.Options = [
            {Id: 1, Name: "One", Checked: true},
            {Id: 2, Name: "Two", Checked: false},
            {Id: 3, Name: "Three", Checked: true}
        ];
        $scope.OldOptions = [];
        $scope.$watch('Options', function (nv) {
            $scope.NewOptions = $.grep(nv.map(function (Option) {
                return Option.Checked ? Option.Name : null;
            }), function(Name) {
                return Name != null;
            });
            log.prepend('Field \"Options\" Changed From=\"' + $scope.OldOptions + '\" To=\"' + $scope.NewOptions + '\"<BR>');
            $scope.OldOptions = $scope.NewOptions;
        }, true);

        /* Start watching specific field */
        $scope.Type = "";
        $scope.$watch('Type', function(newVal, oldVal) {
            if(newVal != oldVal) {
                log.prepend('Field \"Type\" Changed From=\"' + oldVal + '\" To=\"' + newVal + '\"<BR>');
            }
        }, true);
    }]);
</script>

</body>
</html>

Sample Example:

Saturday, December 17, 2016

Rendering text to html with Angular JS

Download example code from here


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Rendering text to html with Angular JS</title>
    <script src="angular.js"></script>
    <script src="angular-sanitize.js"></script>
</head>
<body>

<div data-ng-app="myApp" data-ng-controller="MyController">
    <div ng-bind-html="myHTML()"></div>
</div>

<script type="text/javascript">
    var app = angular.module("myApp", ["ngSanitize"]);

    app.controller("MyController", function ($scope, $sce) {
        $scope.snippet = "<div>This is a DIV element; alert('SURE???')</div>";
        $scope.myHTML = function () {
            return $sce.trustAsHtml($scope.snippet);
        }
    });
</script>

</body>
</html>

Tuesday, December 13, 2016

Add remove required validation in angular dynamically in angular js

<!doctype html>
<html>
<head>
    <title>Add remove required validation in angular dynamically in angular js</title>
    <script src="http://code.angularjs.org/1.2.12/angular.js"></script>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>

<div data-ng-app="myApp" data-ng-controller="MyController">
    <form name="myForm" method="get" validate-form novalidate>
        <div class="container">
            Type:
            <select ng-model="type" my-validation>
                <option value="required">Required</option>
                <option value="not_required">Not Required</option>
            </select>
        </div>
        <div class="container">
            Name:
            <input type="text" name="name" ng-model="name" ng-required="isFieldRequired()" my-validation/>
            <span ng-show="myForm.name.$invalid" style="color:red;font-size:30px;">*</span>
        </div>
        <div><input type="submit" value="Submit"/></div>
    </form>
</div>

<script type="text/javascript">
    var app = angular.module("myApp", []);

    app.controller("MyController", function($scope) {
        $scope.type = "required";
        $scope.isFieldRequired = function() {
            return $scope.type == "required";
        }
    });

    app.directive('validateForm', function () {
        return {
            restrict: 'A',
            link: function ($scope, form) {
                form.on('submit', function () {
                    $(form).find(".container").css("border", "");
                    if($scope.myForm.$invalid) {
                        var error = $scope.myForm.$error;
                         for (var key in $scope.myForm.$error) {
                             for (var index = 0; index < $scope.myForm.$error[key].length; index++) {
                                 var err = $scope.myForm.$error[key][index];
                                 console.log("Field=" + err.$name + ', Error=' + key);
                             }
                         }


                        var firstInvalid = $(form[0].querySelector('.ng-invalid'));

                        if (firstInvalid.length > 0) {
                            firstInvalid.closest(".container").addClass("error_element").css("border", "2px solid red");
                            firstInvalid.focus();
                            return;
                        }
                    }
                    console.log("Form Validated");
                });
            }
        };
    });

    app.directive("myValidation", function() {
        return {
            restrict: "A",
            require: "ngModel",
            link: function(scope, elem, attrs, ctrl) {
                console.log(attrs)
            }
        }
    })
</script>

</body>
</html>

Angularjs Focus Specific Error Input On Form Submit

<!doctype html>
<html>
<head>
    <title>Angularjs Focus Specific Error Input On Form Submit</title>
    <script src="http://code.angularjs.org/1.2.12/angular.js"></script>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>

<div data-ng-app="myApp" data-ng-controller="MyController">
    <form name="myForm" method="get" validate-form novalidate>
        <div class="container">
            Name: <input type="text" name="name" ng-model="name" ng-required="true" ng-maxlength="10" ng-minlength="5" my-validation/>
        </div>
        <div class="container">
            Email: <input type="email" name="email" ng-model="email" ng-required="true" my-validation/>
        </div>
        <div class="container">
            Type:
            <input type="radio" name="type" ng-model="type" value="A" ng-required="true" my-validation/> A
            <input type="radio" name="type" ng-model="type" value="B" ng-required="true" my-validation/> B
            <input type="radio" name="type" ng-model="type" value="C" ng-required="true" my-validation/> C
        </div>
        <div><input type="submit" value="Submit"/></div>
    </form>
</div>

<script type="text/javascript">
    var app = angular.module("myApp", []);

    app.controller("MyController", function($scope) {
        $scope.name = "";
        $scope.email = "";
    });

    app.directive('validateForm', function () {
        return {
            restrict: 'A',
            link: function ($scope, form) {
                form.on('submit', function () {
                    $(form).find(".container").css("border", "");
                    if($scope.myForm.$invalid) {
                        var error = $scope.myForm.$error;
                         for (var key in $scope.myForm.$error) {
                             for (var index = 0; index < $scope.myForm.$error[key].length; index++) {
                                 var err = $scope.myForm.$error[key][index];
                                 console.log("Field=" + err.$name + ', Error=' + key);
                             }
                         }


                        var firstInvalid = $(form[0].querySelector('.ng-invalid'));

                        if (firstInvalid.length > 0) {
                            firstInvalid.closest(".container").addClass("error_element").css("border", "2px solid red");
                            firstInvalid.focus();
                            return;
                        }
                    }
                    alert("Form Validated");
                });
            }
        };
    });

    app.directive("myValidation", function() {
        return {
            restrict: "A",
            require: "ngModel",
            link: function(scope, elem, attrs, ctrl) {
                console.log(attrs)
            }
        }
    })
</script>

</body>
</html>


Thursday, December 1, 2016

Angularjs: Calling a function when ng-repeat has finished


<!DOCTYPE html>
<html>
<head>
    <title>Angularjs: Calling a function when ng-repeat has finished</title>
    <style type="text/css">
        div.log {
            border: 2px solid gray;
            color: black;
            padding: 10px;
            font-size: 20px;
            font-family: monospace;
        }
        div.log div {
            padding: 10px;
        }
    </style>

    <script src="http://code.angularjs.org/1.2.12/angular.js"></script>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>

    <script type="text/javascript">
        var app = angular.module("myApp", []);

        app.controller("MyController", function($scope) {
            $scope.items = [];
            $scope.items.push({"name": "Pritom"});
            $scope.items.push({"name": "Kumar"});

            var log = $(".log");
            $scope.log = function(e) {
                log.prepend("<div>" + e + "</div>");
            }
        })

        app.directive("myCustomValidation", function($timeout) {
            return {
                restrict: "A",
                require: "ngModel",
                link: function(scope, elem, attrs, ctrl) {
                    /**
                     * If you dont use $timeout then nothing found.
                     * You can try yourself.
                     */
                    $timeout(function () {
                        scope.$apply(function () {
                            scope.log(elem.val())
                        })
                    })
                }
            }
        })
    </script>
</head>

<body>
<div data-ng-app="myApp" data-ng-controller="MyController">
    <div>
        <div ng-form="myForm" data-ng-repeat="item in items">
            <div style="border:1px solid blue;padding:10px;">
                <input type="text" name="name" ng-model="item.name" ng-maxlength="10"
                       my-custom-validation required style="width:100%;"/>
            </div>
        </div>
        <div class="log"></div>
    </div>
</div>
</body>
</html>

Result using $timeout:


Result without using $timeout:


Friday, November 25, 2016

How to add custom validation to an AngularJS form field


<!DOCTYPE html>
<html>
<head>
<title>How to add custom validation to an AngularJS form field</title>
<style type="text/css">
    div.log {
        border: 2px solid gray;
        color: black;
        padding: 10px;
        font-size: 20px;
        font-family: monospace;
    }
    div.log div {
        padding: 10px;
    }
</style>

<script src="http://code.angularjs.org/1.2.12/angular.js"></script>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>

<script type="text/javascript">
    var app = angular.module("myApp", []);

    app.controller("MyCustomValidationController", function($scope, $http) {
        $scope.items = [];
        $scope.items.push({"name": "Pritom", "type": "A"});
        $scope.items.push({"name": "Kumar", "type": "B"});

        var log = $(".log");
        $scope.log = function(e) {
            log.prepend("<div>" + e + "</div>");
        }

        $scope.error = function(e) {
            log.prepend("<div style='color:red;'>" + e + "</div>");
        }
    })

    app.directive("myCustomValidation", function() {
        return {
            restrict: "A",
            require: "ngModel",         
            link: function(scope, elem, attrs, ctrl) {
                ctrl.$parsers.unshift(function(v) {
                    scope.$evalAsync(function() {
                        scope.log("Parsers=" + v)
                    })
                    if(v.length > 10) {
                        ctrl.$setValidity('myCustomValidation', false)
                    }
                    else {
                        ctrl.$setValidity('myCustomValidation', true)
                    }
                    return v
                })
                ctrl.$formatters.unshift(function(v) {
                    scope.$evalAsync(function() {
                        scope.log("Formatters=" + v)
                    })
                    return v
                })
                elem.on('keyup', function (evt) {
                    if(ctrl.$error.maxlength) {
                        scope.$evalAsync(function() {
                            scope.error("Maxlength")
                        })
                    }
                    if(ctrl.$error.required) {
                        scope.$evalAsync(function() {
                            scope.error("Required")
                        })
                    }
                    if(ctrl.$error.myCustomValidation) {
                        scope.$evalAsync(function() {
                            scope.error("MyCustomValidation")
                        })
                    }
                })
            }
        }
    })
</script>
</head>

<body>
 <div data-ng-app="myApp" data-ng-controller="MyCustomValidationController">
     <div>
         <div ng-form="myForm" data-ng-repeat="item in items">
             <div style="border:1px solid blue;padding:10px;">
                <input type="text" name="name" ng-model="item.name" ng-maxlength="10" 
                       my-custom-validation required style="width:50%;"/>
                <select ng-model="item.type" my-custom-validation required style="width:48%;" name="type">
                    <option value="">None</option>
                    <option value="A">A</option>
                    <option value="B">B</option>
                    <option value="C">C</option>
                </select>
             </div>
         </div>
         <div class="log"></div>
     </div>
 </div>
</body>
</html>


Wednesday, November 16, 2016

Angular-js infinity scroll to load more data on window or other element scrolling


<!DOCTYPE html>
<html>
    <head>
        <title>Infinite scrolling to load more data using angular-js</title>
        <style type="text/css">
            div.scroll-test {
                height: 100%;
                background: #123213;
                color: #fff;
                overflow: auto;
                margin: 0 auto;
                padding: 0.5em;
            }
        </style>
        
        <script src="http://code.angularjs.org/1.2.12/angular.js"></script>
        <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
        
        <script type="text/javascript">
            var app = angular.module("myApp", []);
           
            app.controller("ScrollController", function($scope, $http) {
                $scope.items = ["You have to scroll down to load more items..."];
                $scope.loading = false;
                $scope.counter = 0;
                $scope.rows = 1;
                
                var s = "----------------------------------------------------";
                s += "-------------------------------------------------------";
                s += "-------------------------------------------------------";
                
                $scope.loadMore = function() {
                    if(!$scope.loading) {
                        $scope.loading = true;
                        $http({
                            method: "GET",
                            url: "http://localhost/scroll/data.html?counter=" + ($scope.counter++)
                        }).success(function(data, status, header, config) {
                            $scope.loading = false;
                            data = data.split("\n");
                            for(i = 0; i < data.length - 1; i++) {
                                $scope.items.push(($scope.rows++) + "=" + data[i]);
                            }
                            $scope.items.push(($scope.rows++) + s);
                        });
                    }
                };
                
                var params = {};
                window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str, key, value) {
                    params[key] = decodeURIComponent(value.replace(/\+/g, ' '));
                });
                var type = params.type === undefined ? '' : params.type;
                
                $scope.window = true;
                if(type == 'window') {
                    //Initializing the list
                    $scope.loadMore();
                }
                else if(type == 'div') {
                    $scope.window = false;
                    $("div.scroll-test").height(window.innerHeight - 130);
                    //Initializing the list
                    $scope.loadMore();
                }
                else {
                    $scope.items.push("You have to define 'type' parameter in url & value would be 'window' or 'div' as ?type=window");
                }
            });
            
            app.directive("windowScroll", function ($window) {
                return function(scope, element, attrs) {
                    angular.element($window).bind("scroll", function() {
                        if(scope.window && $window.pageYOffset + $(window).height() + 50 >= $(document).height()) {
                            scope.$apply(attrs.windowScroll);
                        }
                    });
                };
            });
           
            app.directive("divScroll", function() {
                return {    
                    restrict: 'A',
                    link: function(scope, element, attrs) {
                        var raw = element[0];
                        element.bind("scroll", function() {
                            if(!scope.window && raw.scrollTop + raw.offsetHeight + 50 >= raw.scrollHeight) {
                                scope.$apply(attrs.divScroll);
                            }
                        });
                    }
                }
            });
        </script>
    </head>

    <body>
         <div data-ng-app="myApp" data-window-scroll="loadMore()" data-ng-controller="ScrollController">
             <div>
                 <div class="scroll-test" data-div-scroll="loadMore()">
                     <p data-ng-repeat="item in items">
                         {{item}}
                     </p>
                 </div>
                <h1><i>INFINITE SCROLLING IN ANGULAR-JS<span data-ng-show="loading"> (Loading items...)</span></i></h1>              
             </div>       
         </div>
    </body>
</html>

Friday, November 4, 2016

Angularjs ajax get or post method example from controller


app.controller('TestController', function($scope, $http) {
    $scope.name = "Pritom Kumar";
    $scope.posts = ["a", "b"];
    
    $http.post('lists_json', {id: 1, name: $scope.name}).
    success(function(response, status, headers, config) {
        console.log("Success=" + response);
    }).
    error(function(response, status, headers, config) {
        console.log("Error=" + response);
    });
    
    $http.get('lists_json?id=1&name='+$scope.name+"&list="+$scope.posts).
    success(function(response, status, headers, config) {
        console.log("Success=" + response);
    }).
    error(function(response, status, headers, config) {
        console.log("Error=" + response);
    });
});