Home Running AngularJS controller when view is loaded
Reply: 0

Running AngularJS controller when view is loaded

user25380
1#
user25380 Published in April 26, 2018, 1:42 pm

I have an angularJS single page application that loads view per click.

My login and Index is in one html. I have manipulated it by ng-show and ng-if

The flow goes like this: Index.html and IndexController.js: Login page has a ng-show="!isLogin" then if it is authenticated then isLogin = true;

so I will be able to see my home page. The code goes like this

<section id="content">
  <div ng-view>
  </div>
</section>

then I have a default.html that contains the first page to be seen after the 'isLogin' became true which have the controller DashboardController.js

but the thing is the controller won't run unless I click the button on the nav

See the "Overdue Bills". It didn't load unless I click the "Dashboard" on my NavBar

so how do I run my controller after I logged in? any help will be appreciated This project is for educational purpose

Thank you

EDIT: DashboardController.js

var dashboardController = angular.module('DashboardController', []).controller('DashboardController', function ($http, $scope, $sessionStorage,$window,SweetAlert,BillService,$filter) {
    (function init() {
        $(document).ready(function() {
            $('select').material_select();
            $('.modal-trigger').leanModal();
            $('.modal').modal();

        });
        $scope.overDue = [];

        BillService.getBillbyBusinessId($sessionStorage.currentBusiness.businessId).then(function (response) {
            angular.forEach(response.data, function (value) {
                if (value.status === "active") {
                    var date = new Date();
                    date = $filter('date')(date, "MM-dd-yyyy");
                    if(value.dueDate < date){
                        $scope.overDue.push(value);
                    }
                }

            });
        });

        var obj=[];
        for(var i=1;i<5;i++){
            obj.push({Id: i, Value: "Value "+i});
        }
        $scope.ItemList=obj;
    })();


    //
    //$scope.showCreateForm = function(){
    //    $('#modal1').show();
    //}




});

dashboardController.directive("select2", function ($timeout, $parse) {
    return {
        restrict: 'AC',
        require: 'ngModel',
        link: function (scope, element, attrs) {
            $timeout(function () {
                element.select2();
                element.select2Initialized = true;
            });

            var refreshSelect = function () {
                if (!element.select2Initialized) return;
                $timeout(function () {
                    element.trigger('change');
                });
            };

            var recreateSelect = function () {
                if (!element.select2Initialized) return;
                $timeout(function () {
                    element.select2('destroy');
                    element.select2();
                });
            };

            scope.$watch(attrs.ngModel, refreshSelect);

            if (attrs.ngOptions) {
                var list = attrs.ngOptions.match(/ in ([^ ]*)/)[1];
                // watch for option list change
                scope.$watch(list, recreateSelect);
            }

            if (attrs.ngDisabled) {
                scope.$watch(attrs.ngDisabled, refreshSelect);
            }
        }
    };
});

Index.html

</head>

<body class="cyan">
<div id="loader-wrapper">
    <div id="loader"></div>
    <div class="loader-section section-left"></div>
    <div class="loader-section section-right"></div>
</div>

<div id="login" ng-show="!isLogin">
    <div class="login">
        <div id="login-page" class="row">
            <div class="col s12 z-depth-4 card-panel" style="padding-bottom: 10px ">
                <form class="login-form" ng-submit="login()" ng-show="!businessPicker">
                    <div class="row">
                        <div class="input-field col s12 center">
                            <img src="images/codegum_logo.png" alt=""
                                 class="circle responsive-img valign profile-image-login">

                            <p class="center login-form-text">Codegum Inc.</p>
                        </div>
                    </div>
                    <div class="row margin">
                        <div class="input-field col s12">
                            <i class="mdi-social-person-outline prefix"></i>
                            <input id="username" type="text" ng-model="username">
                            <label for="username" class="center-align">Username</label>
                        </div>
                    </div>
                    <div class="row margin">
                        <div class="input-field col s12">
                            <i class="mdi-action-lock-outline prefix"></i>
                            <input id="password" type="password" ng-model="password">
                            <label for="password">Password</label>
                        </div>
                    </div>
                    <div class="row">
                        <div class="input-field col s12 m12 l12  login-text">
                            <input type="checkbox" id="remember-me"/>
                            <label for="remember-me">Remember me</label>
                        </div>
                    </div>
                    <div class="row">
                        <div class="input-field col s12">
                            <button type="submit" class="btn btn-default">Login</button>
                        </div>
                    </div>
                    <div class="row">
                        <div class="input-field col s6 m6 l6">
                            <p class="margin medium-small"><a href="/registration">Register Now!</a></p>
                        </div>
                        <div class="input-field col s6 m6 l6">
                            <p class="margin right-align medium-small"><a href="/login">Forgot
                                password ?</a></p>
                        </div>
                    </div>

                </form>
                <div id="chooseBusiness" ng-show="businessPicker">
                    <h5 style="text-align:center;margin-bottom:15px; font-size: 20px;">Choose Business</h5>
                    <ul dir-paginate="item in businessRole | itemsPerPage: 5" id="profile-page-about-details" class="collection z-depth-1" style="margin-bottom:0px !important; margin-top: 0px !important;">
                        <li class="collection-item">
                            <div class="row" style="margin-bottom:0px !important; margin-top: 0px !important; " ng-click="chosenBusiness(item.business)">
                                <div class="col s5 grey-text darken-1"><i style="font-size:20px;" class="mdi-action-wallet-travel"></i></div>
                                <div class="col s7 grey-text text-darken-4 text-left">{{item.businessName}}</div>
                            </div>
                        </li>
                    </ul>
                    <dir-pagination-controls class="center"></dir-pagination-controls>

                    <a class="btn waves-effect waves-light " type="submit" name="action" style="margin-bottom: 10px; margin-top:10px; margin-right:55px; margin-left:55px;" ng-click="businessReg()">Create a Business</a>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row" ng-show="createBusiness">
    <div class="col s8 offset-s2">

        <div id="breadcrumbs-wrapper">
            <div class="col s12">
                <h5 class="breadcrumbs-title">Create Business</h5>
                <ol class="breadcrumbs">
                    <li><a>Select Business</a></li>

                    <li class="active">Create Business</li>
                </ol>
                <div class="divider"></div>
            </div>
        </div>


        <div class="card-panel">
            <div class="row">
                <div class="input-field col s12">
                    <input id="companyName" type="text" class="validate" ng-model="companyName"
                           ng-class="{invalid : validation.companyName}">
                    <label for="companyName" ng-class="{invalid : validation.companyName}"
                           data-error="Business/Company Name is required">Business/Company Name</label>
                </div>
            </div>
            <div class="row"></div>
            <div class="row">
                <div class="input-field col s12">
                    <select id="businessType" ng-model="typeBusiness" ng-class="{invalid : validation.businessType}">
                        <option value="" disabled selected>Choose your option</option>
                        <option value="Artist, Photographers & Creative Types">Artist, Photographers & Creative Types</option>
                        <option value="Consultant and Professionals">Consultant and Professionals</option>
                        <option value="Financial Services">Financial Services</option>
                        <option value="General: I make or sell a PRODUCT">General: I make or sell a PRODUCT</option>
                        <option value="General: I provide a SERVICE">General: I provide a SERVICE</option>
                        <option value="Hair, Spa & Aesthetics">Hair, Spa & Aesthetics</option>
                        <option value="Medical, Dental, Health">Medical, Dental, Health</option>
                        <option value="Non-profits, Association & Groups">Non-profits, Association & Groups</option>
                        <option value="Real Estate, Construction & Home Improvement">Real Estate, Construction & Home Improvement</option>
                        <option value="Retailers, Resellers & Sales">Retailers, Resellers & Sales</option>
                        <option value="Web, Tech & Media">Web, Tech & Media</option>
                    </select>
                    <label for="businessType" ng-class="{invalid : validation.businessType}"
                           data-error="Business Type is required">Business Type</label>
                </div>
            </div>
            <div class="row"></div>
            <div class="row">
                <div class="input-field col s12">
                    <select id="currency" ng-model="businessCurrency" ng-class="{invalid : validation.currency}">
                        <option value="" disabled selected>Choose your option</option>
                        <option value="PHP - Philippine Peso">PHP - Philippine Peso</option>
                    </select>
                    <label for="currency" ng-class="{invalid : validation.currency}"
                           data-error="Business Currency is required">Business Currency</label>
                </div>
            </div>
            <div class="row"></div>
            <div class="row">
                <div class="input-field col s12">
                    <select id="country" type="text" class="validate" ng-model="country"
                           ng-class="{invalid : validation.country}">
                        <option value="" disabled selected>Choose your option</option>
                        <option value="Philippines">Philippines</option>
                    </select>
                    <label for="country" ng-class="{invalid : validation.country}"
                           data-error="Country is required">Country</label>
                </div>
            </div>
            <div class="row"></div>
            <div class="row">
                <div class="col s4 offset-s4">
                    <a class="btn waves-effect waves-light blue" ng-click="makeBusiness()">Create</a>
                    <a class="btn waves-effect waves-light blue" ng-click="cancelRequest()">Cancel </a>
                </div>
            </div>

        </div>
        <!--card panel-->
    </div>
    <!--col s8-->
</div>

<div id="index" ng-show="showWeb">
    <!-- START HEADER -->
    <header id="header" class="page-topbar">
        <!-- start header nav-->
        <div class="navbar-fixed">
            <nav class="navbar-color">
                <div class="nav-wrapper">
                    <ul class="left">
                        <li><h1 class="logo-wrapper"><a href="#" class="brand-logo darken-1"><img
                                src="images/materialize-logo.png" alt="materialize logo"></a> <span class="logo-text">Materialize</span>
                        </h1></li>
                    </ul>

                    <ul class="right hide-on-med-and-down">
                        <li><a href="javascript:void(0);"
                               class="waves-effect waves-block waves-light notification-button"
                               data-activates="notifications-dropdown"><i class="mdi-social-notifications">
                            <small class="notification-badge">5</small>
                        </i>
                        </a>
                        </li>
                    </ul>

                    <!-- notifications-dropdown -->
                    <ul id="notifications-dropdown" class="dropdown-content">
                        <li>
                            <h5>NOTIFICATIONS <span class="new badge">5</span></h5>
                        </li>
                        <li class="divider"></li>
                        <li>
                            <a href="#!"><i class="mdi-action-add-shopping-cart"></i> A new order has been placed!</a>
                            <time class="media-meta" datetime="2015-06-12T20:50:48+08:00">2 hours ago</time>
                        </li>
                        <li>
                            <a href="#!"><i class="mdi-action-stars"></i> Completed the task</a>
                            <time class="media-meta" datetime="2015-06-12T20:50:48+08:00">3 days ago</time>
                        </li>
                        <li>
                            <a href="#!"><i class="mdi-action-settings"></i> Settings updated</a>
                            <time class="media-meta" datetime="2015-06-12T20:50:48+08:00">4 days ago</time>
                        </li>
                        <li>
                            <a href="#!"><i class="mdi-editor-insert-invitation"></i> Director meeting started</a>
                            <time class="media-meta" datetime="2015-06-12T20:50:48+08:00">6 days ago</time>
                        </li>
                        <li>
                            <a href="#!"><i class="mdi-action-trending-up"></i> Generate monthly report</a>
                            <time class="media-meta" datetime="2015-06-12T20:50:48+08:00">1 week ago</time>
                        </li>
                    </ul>
                </div>
            </nav>
        </div>
        <!-- end header nav-->
    </header>
    <!-- END HEADER -->
    <!-- //////////////////////////////////////////////////////////////////////////// -->

    <!-- START MAIN -->
    <div id="dash"></div>
    <div id="main">
        <!-- START WRAPPER -->
        <div class="wrapper">

            <!-- START LEFT SIDEBAR NAV-->
            <aside id="left-sidebar-nav">

                <ul id="slide-out" class="side-nav fixed leftside-navigation">
                    <li class="user-details cyan darken-2">
                        <div class="row">
                            <div class="col col s4 m4 l4">
                                <img src="images/avatar.jpg" alt="" class="circle responsive-img align profile-image">
                            </div>
                            <div class="col col s8 m8 l8">
                                <ul id="profile-dropdown" class="dropdown-content">
                                    <li><a href="#!AccountProfile"><i class="mdi-action-face-unlock"></i> Profile</a>
                                    </li>
                                    <li><a href="#"><i class="mdi-action-settings"></i> Settings</a>
                                    </li>
                                    <li><a href="#"><i class="mdi-communication-live-help"></i> Help</a>
                                    </li>
                                    <li class="divider"></li>
                                    <li><a href="#"><i class="mdi-action-lock-outline"></i> Lock</a>
                                    </li>
                                    <li><a ng-click="logout()"><i class="mdi-hardware-keyboard-tab"></i> Logout</a>
                                    </li>
                                </ul>
                                <a class="btn-flat dropdown-button waves-effect waves-light white-text profile-btn"
                                   href="#" data-activates="profile-dropdown">Hey, {{user.firstName}}<i
                                        class="mdi-navigation-arrow-drop-down right"></i></a>

                                <p class="user-roal">{{businessData.companyName}}</p>
                                <p class="user-roal" style="line-height:5px;">{{businessRole.roles}}</p>
                            </div>
                        </div>
                    </li>


                    <li class="bold active"><a href="#" class="waves-effect waves-cyan"><i
                            class="mdi-action-dashboard"></i> Dashboard</a>
                    <li class="no-padding">
                        <ul class="collapsible collapsible-accordion">
                            <li class="bold"><a class="collapsible-header  waves-effect waves-cyan"><i
                                    class="mdi-editor-attach-money"></i>Sales</a>

                                <div class="collapsible-body">
                                    <ul>
                                        <li><a href="#!Customers">Customer</a></li>
                                        <li><a href="#!SalesPNS">Products and Services</a></li>
                                    </ul>
                                </div>
                            </li>

                            <li class="bold"><a class="collapsible-header  waves-effect waves-cyan"><i
                                    class="mdi-action-shopping-cart"></i>Purchases</a>

                                <div class="collapsible-body">
                                    <ul>
                                        <li><a href="#!Bills">Bills</a></li>
                                        <li><a href="#!Vendors">Vendors</a></li>
                                        <li><a href="#!PurchasesPNS">Products and Services</a></li>

                                    </ul>
                                </div>
                            </li>
                            <li class="bold"><a class="collapsible-header  waves-effect waves-cyan"><i
                                    class="mdi-action-account-balance"></i>Accounting</a>

                                <div class="collapsible-body">
                                    <ul>
                                        <li><a href="#!Transactions">Transactions</a></li>
                                        <li><a href="#!Starting">Chart of Accounts</a></li>
                                    </ul>
                                </div>
                            </li>
                            <li ng-if="businessRole.roles == 'Owner'||businessRole.roles == 'Manager'"  class="bold"><a href="#!Reports" class="waves-effect waves-cyan"><i
                                    class="mdi-content-report"></i>Reports</a>
                            </li>
                            <li ng-if="businessRole.roles == 'Owner'||businessRole.roles == 'Manager'" class="bold"><a href="#!Logs" class="waves-effect waves-cyan"><i
                                    class="mdi-av-my-library-books"></i>Logs</a>
                            </li>
                            <li ng-if="businessRole.roles == 'Owner'||businessRole.roles == 'Manager'"  class="bold"><a href="#!Reference" class="waves-effect waves-cyan"><i
                                    class="mdi-action-settings"></i>Reference</a>
                            </li>
                        </ul>
                        <a href="#" data-activates="slide-out"
                           class="sidebar-collapse btn-floating btn-medium waves-effect waves-light hide-on-large-only cyan"><i
                                class="mdi-navigation-menu"></i></a>
                    </li>
                </ul>
                <a href="#" data-activates="slide-out"
                   class="sidebar-collapse btn-floating btn-medium waves-effect waves-light hide-on-large-only cyan"><i
                        class="mdi-navigation-menu"></i></a>
            </aside>
            <!-- END LEFT SIDEBAR NAV-->

            <!-- //////////////////////////////////////////////////////////////////////////// -->


            <!-- END LEFT SIDEBAR NAV-->

            <section id="content">
                <div ng-view>


                </div>
            </section>
        </div>
    </div>
</div>

<!-- END MAIN -->


<!-- //////////////////////////////////////////////////////////////////////////// -->

<!-- START FOOTER -->
<footer class="page-footer" ng-show="isLogin">
    <div class="footer-copyright">
        <div class="container">
            Copyright © 2018 <a class="grey-text text-lighten-4"
                                href="http://codegum.ph/"
                                target="_blank">Codegum
            Inc.</a> All rights reserved.
                <span class="right"> Design and Developed by <a class="grey-text text-lighten-4"
                                                                href="http://facebook.com/xreign09">Team 1-UP</a></span>
        </div>
    </div>
</footer>


<!-- END FOOTER -->


<!-- ================================================
Scripts
================================================ -->



</body>

</html>

EDIT2: for NTP

 <body ng-init="change=true">
    <button ng-click="change = !change">Click to initialize other controller</button>
    <div ng-if="change" ng-controller="MainCtrl">
      first controller
      <div ng-if="!change" ng-controller="SubCtrl">
      second controller
    </div>
    </div>

  </body>
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.459203 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO