AngularJS - Navigation between pages if login is successful (with different html pages and controllers)

Viewed 299

Helo, I am working on an AngularJS app. I need help with routing. I am trying to navigate to index.html IF the login is successful (login.html). There are lots of examples about it but I could not get them to work with my application. Recently, I tried this , but still no luck.

I have 2 html pages; index.html and login.html. Also 2 seperate controller files for them; controller.js and logincontroller.js

Below my logincontroller.js

var myLogin = angular.module('myLogin', [])

myLogin.controller('MyLoginController', function($scope, $http)
{

$scope.Login = function(){

        $http(
                {...
                })
        .then(
                function successCallback(response) {
                    $scope.loginresponse = response.data;
                    if($scope.loginresponse=="OK"){
                       // here go to index page
                    }
                }, 
                function errorCallback(response) {
                    alert("Failed to login!");
        });
    }
});

my controller.js(for index.html)

var myApp = angular.module('myApp',[ 'ui.bootstrap.datetimepicker', 'ngclipboard', 'hljs'])


myApp.controller("MyController", function TimeCtrl($scope, $timeout, $filter, $http, $window) {


});

in case needed part of: login.html

<!DOCTYPE html>
<html lang="en" data-ng-app="myLogin"> 
<meta charset="UTF-8">
<head>

<meta name="viewport" content="width=device-width, initial-scale=1">


<script src="web-admin/libs/angular.js"></script>
<script src="web-admin/controllers/logincontroller.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script> 
...
</head>
<body>
<div data-ng-controller="MyLoginController"> ...

index.html:

<!DOCTYPE html>
<html lang="en" data-ng-app="myApp"> 
<meta charset="UTF-8">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="web-admin/libs/angular.js"></script>
<script src="web-admin/controllers/controller.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
...
</head>

<body>
    <div data-ng-controller="MyController">

I am confused about lots of things; one of them is that where should I put "config"? in controllerjs or logincontrollerjs or in a seperate file. If in seperate file, should I change data-ng-app in html files etc. Thanks in advance!

2 Answers

The main issue here is that your modules are not connected.

When declaring the angular.module('myLogin', []), you are telling angular to give you a new module which has no dependencies. When you then declare angular.module('myApp',[ 'ui.bootstrap.datetimepicker', 'ngclipboard', 'hljs']), you tell angular to create a new module, with some dependencies, but don't supply the 'myLogin' module. So now you got two modules which don't know about each other.

I recommend you to use one module and reuse it instead. Reuse the 'myApp' for both by just refering to the same instance like angular.module('myApp'), (if you don't pass an array to the module, it will fetch a module instead of creating a new)

Then, to solve your redirect problem. Look at the link you posted. You are missing the ngRoute dependency to the module. When that is injected you can use the $location service and perform $location.path("home"); in the login success callback.

Here is sample code, how to link module and controllers.

app.js

it's main app.js file. you need to config and collect all required information here.

(function() {
    'use strict';
    var wmApp = angular.module('wmApp', ['ngRoute', 'ngSanitize']);

    // it's router, I cannot create separate file because of error message
    wmApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
        $routeProvider
            .when('/', {
                templateUrl:  '/login.html',
                controllerAs:  'loginCtrl'
            })
            .otherwise({redirectTo:'/'});
        $locationProvider.html5Mode(false);
    }]);

    // Declare all require variable here, never declare controller files for common usage.
    wmApp.run(['$rootScope', function ($rootScope, utilService, apiService) {
        $rootScope.headers = {

        };
    }]);
})();

here is login controller file In this controller file, there is service is included apiService.

(function() {
    'use strict';
    var wmApp = angular.module('wmApp');

    wmApp.controller('loginCtrl', LoginCtrl);
    LoginCtrl.$inject = ['$scope', '$window', '$routeParams', 'apiService'];
    function LoginCtrl($scope, $window, $routeParams, apiService) {

    }
})();

Here is services file as well as modules file

(function() {
    'use strict';
    var wmApp = angular.module('wmApp');
    angular.module('wmApp').service('apiService', ['$rootScope', '$q', function($rootScope, $q) {
        this.apiPostRequest = (paymentId, params) => {
            var deferred = $q.defer();
            return deferred.promise;
        };

    }]);
})();

here is main html file

<!DOCTYPE html>
<html lang="en">
    <head>
        <base href="/">
    </head>
    <body ng-app="wmApp" class="bgcolor">
        <div ng-view=""></div>
        <script src="/scripts/app.js"></script>
        <script src="/scripts/controllers/login.controller.js"></script>
        <script src="/scripts/services/apiService.js"></script>
    </body>
</html>
Related