Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to route CodeIgniter with Angular.js? [duplicate]

I'm trying to use Angular.js and CodeIgniter together.

With ngRoute in my app, I'm setting in my main.js:

$locationProvider.html5Mode(true);

$routeProvider.when('/test', {
    templateUrl: 'partials/test.html'
});

$routeProvider.otherwise({
    templateUrl: 'partials/home.html'
});

In my routes.php, I'm setting:

$route['default_controller'] = 'home';
$route['(:any)'] = "home";

And in my home/index.php, I have the <ng-view></ng-view>.

The thing is, without the html5Mode(true) (with /#/ on the URL) everything works fine. But otherwise, the partials file works, but the page reloads anyway.

In Inspector Elements, things look like this:

partials/test.html loaded, but the page realoded, and the error "ngView: undefined" showed up

partials/test.html loaded, but the page realoded, and the error "ngView: undefined" showed up.

I'm still learning Angularjs. Anyone can help?

like image 211
Paula Fleck Avatar asked May 13 '16 12:05

Paula Fleck


1 Answers

this is a production form (i´m using htaccess)

in the js folder create a app.js js/app.js

//create app module
var app = angular.module("app", []);

//login configuration
app.config(function($routeProvider){
    $routeProvider.when("/login", {
        controller : "loginController",
        templateUrl : "templates/login.html"
    })
    .when("/home", {
        controller : "homeController",
        templateUrl : "templates/home.html"
    })
});

js/controllers/controllers.js

//save & delete sessions
app.factory("sesionesControl", function(){
    return {
        //obtenemos una sesión //getter
        get : function(key) {
            return sessionStorage.getItem(key)
        },
        //creamos una sesión //setter
        set : function(key, val) {
            return sessionStorage.setItem(key, val)
        },
        //limpiamos una sesión
        unset : function(key) {
            return sessionStorage.removeItem(key)
        }
    }
})

//simple message in bad login
app.factory("mensajesFlash", function($rootScope){
    return {
        show : function(message){
            $rootScope.flash = message;
        },
        clear : function(){
            $rootScope.flash = "";
        }
    }
});

//angular login & logout
app.factory("authUsers", function($http, $location, sesionesControl, mensajesFlash){
    var cacheSession = function(email){
        sesionesControl.set("userLogin", true);
        sesionesControl.set("email", email);
    }
    var unCacheSession = function(){
        sesionesControl.unset("userLogin");
        sesionesControl.unset("email");
    }

    return {
        //return authUsers
        login : function(user){
            return $http({
                url: 'http://localhost/login_ci_angularjs/login/loginUser',
                method: "POST",
                data : "email="+user.email+"&password="+user.password,
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).success(function(data){
                if(data.respuesta == "success"){
                    //if true clear flash messages
                    mensajesFlash.clear();
                    //create session with email
                    cacheSession(user.email);
                    //redirect to home
                    $location.path("/home");
                }else if(data.respuesta == "incomplete_form"){
                    mensajesFlash.show("The email & user are required");
                }else if(data.respuesta == "failed"){
                    mensajesFlash.show("The email ore password are wrong");
                }
            }).error(function(){
                $location.path("/")
            })
        },
        //close session
        logout : function(){
            return $http({
                url : "http://localhost/login_ci_angularjs/login/logoutUser"
            }).success(function(){
                //delete session in sessionStorage
                unCacheSession();
                $location.path("/login");
            });
        }
    }
})

app.controller("homeController", function($scope, sesionesControl, authUsers){
    $scope.email = sesionesControl.get("email");
    $scope.logout = function(){
        authUsers.logout();
    }
})

//permisos
app.run(function($rootScope, $location, authUsers){
    //url that the user can access
    var rutasPrivadas = ["/home","/info","/login"];
    $rootScope.$on('$routeChangeStart', function(){
        if(in_array($location.path(),rutasPrivadas) && !authUsers.isLoggedIn()){
            $location.path("/login");
        }
        //if user go to login (if the session exist redirect to home)
        if(($location.path() === '/login') && authUsers.isLoggedIn()){
            $location.path("/home");
        }
    })
})

//controller loginController
app.controller("loginController", function($scope, $location, authUsers){
    $scope.user = { email : "", password : "" }
    authUsers.flash = "";
    //submit form
    $scope.login = function(){
        authUsers.login($scope.user);
    }
})

//if user has permissions in the url
function in_array(needle, haystack, argStrict){
  var key = '',
  strict = !! argStrict;

  if(strict){
    for(key in haystack){
      if(haystack[key] === needle){
        return true;
      }
    }
  }else{
    for(key in haystack){
      if(haystack[key] == needle){
        return true;
      }
    }
  }
  return false;
}

templates/login.htm

<form name="loginUserForm">
    <fieldset>
        <legend>form login</legend>

        <div class="row">
            <div ng-show="flash">
                <div data-alert class="alert-box alert round">{{ flash }}</div>
            </div>
            <div class="large-12 columns">
                <label>Email</label>
                <input type="email" required placeholder="[email protected]" ng-model="user.email">
            </div>
            <div class="large-12 columns">
                <label>Password</label>
                <input type="password" required placeholder="Password" ng-model="user.password">
            </div>

            <button type="submit" ng-disabled="!loginUserForm.$valid" ng-click="login(user)" class="button expand round">Login</button>
        </div>

    </fieldset>
</form>

Login.php controller

class Login extends CI_Controller{
    public  function __construct(){
        parent::__construct();
    }
    public function index(){
        $this->load->view("login");
    }

    //called from angular controller.js
    public function loginUser(){
        if($this->input->post("email") && $this->input->post("password"))
        {
            $this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
            $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean');
            if($this->form_validation->run() == false){
                echo json_encode(array("respuesta" => "incomplete_form"));
            }else{
                $this->load->model("login_model");
                $email = $this->input->post("email");
                $password = $this->input->post("password");
                $loginUser = $this->login_model->loginUser($email,$password);
                if($loginUser === true){
                    echo json_encode(array("respuesta" => "success"));
                }else{
                    echo json_encode(array("respuesta" => "failed"));
                }
            }
        }else{
            echo json_encode(array("respuesta" => "incomplete_form"));
        }
    }

    public function logoutUser(){
        $this->session->sess_destroy();
    }
}

apllications/views/login.php

<!DOCTYPE  html>
<html lang="es" ng-app="app">
<head>
    <meta charset="UTF-8" />
    <title>CI & Angular</title>
</head>
<body>
<!-- with this ng-view, we load all views -->
<div class="row" ng-view></div>
<script type="text/javascript" src="<?php echo base_url() ?>js/angular.js"></script>
<script type="text/javascript" src="<?php echo base_url() ?>js/app.js"></script>
<script type="text/javascript" src="<?php echo base_url() ?>js/controllers/controllers.js"></script>
</body>
</html>

templates/home.html

<h3 class="subheader">Hello {{ email }}</h3>
<button ng-click="logout()" class="large-12 button expand">Logout</button>
like image 55
elddenmedio Avatar answered Nov 04 '22 15:11

elddenmedio