This question already has an answer here:
AngularJS and Codeigniter - Combination & Data Transfer
(1 answer)
Closed 6 years ago.
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.
I'm still learning Angularjs. Anyone can help?
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="mail#mail.com" 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>
Related
I have a problem, my page after login is not redirecting to main page. I have checked condition login working when I use $window.location. I want to use angular-route to prevent user without login to access my main menu. If I use $window.location, the user can access my main menu without login. Here is my js file
app.config(function($routeProvider){
$routeProvider
.when('/',{
templateUrl:'index.html'
})
.when('/mainmenu',{
resolve:{
"check":function($location,$rootScope){
if (!$rootScope.loggedIn) {
$location.path('/');
}
}
},
templateUrl:'content/mainmenu2.html'
})
.otherwise({
redirectTo:'/'
});
});
app.controller("logincont", ['$scope','$http','$window','$rootScope','$location',function($scope,$http,$window,$rootScope,$location){
$scope.login = function () {
$http.get('http://localhost:8089/MonitoringAPI/webresources/login?a='+$scope.userid+'&d='+$scope.password).then(function(response){
$scope.reslogin = response.data;
if($scope.reslogin == null)
{
alert('Login Incorrect');
}
else
{
$rootScope.loggedIn = true;
$location.path('/mainmenu');
}
});
};
}]);
here is my html
<form>
<h1 class="tengah"> Form Login </h1>
<div class="form-group">
<label for="inputId">User Id</label>
<input type="text" class="form-control" ng-model="userid" placeholder="userid" required>
</div>
<div class="form-group">
<label for="inputPassword">Password</label>
<input type="password" class="form-control" ng-model="pass" placeholder="Password" required>{{password}}
</div>
<button type="submit" class="btn btn-primary" ng-click="login()">
<span class="fa fa-sign-out"></span>Login</button>
</form>
You can do it by using a flag allowUnauth on the routes those you don't want to authenticate for e.g login and then change your routing like:-
app.config(function($routeProvider){
$routeProvider
.when('/',{
templateUrl:'index.html',
allowUnauth:true
})
.when('/mainmenu',{
templateUrl:'content/mainmenu2.html'
}).otherwise({
redirectTo:'/'
});
});
var unauthRoutes= [];
angular.forEach($route.routes, function(route, path) {
// push route onto unauthRoutes if it has a truthy allowUnauth value
route.allowUnauth && (unauthRoutes.push(path));
});
$rootScope.$on('$routeChangeStart', function(event, nextLoc, currentLoc)
{
var atuhRoute= (-1 === unauthRoutes.indexOf($location.path()));
if(atuhRoute && !$rootScope.loggedIn) {
$location.path('/');
}
});
Working plunker
Try something like
"use strict";
configureApp.$inject = ['$routeProvider'];
function configureApp($routeProvider) {
$routeProvider
.when('/mainmenu', {
resolve: {
ensureAthenticated: (function() {
ensureAthenticated.$inject = ['$rootScope'];
function ensureAthenticated($rootScope) {
if(!$rootScope.loggedIn) {
return Promise.reject('not athenticated');
}
else return Promise.resolve();
};
return ensureAthenticated;
}())
},
templateUrl:'content/mainmenu2.html'
})
.otherwise('/');
}
app.config(configureApp);
I have this bug when I work authentification between angular js and symfony , I have bug in front end (angular js) :
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.5/$injector/modulerr?p0=angularApp&p1=Error%3A%20%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.6.5%2F%24injector%2Fmodulerr%3Fp0%3Drestangular%26p1%3DTypeError%253A%2520Cannot%2520read%2520property%2520'isUndefined'%2520of%2520undefined%250A%2520%2520%2520%2520at%2520Object.Configurer.init%2520(http%253A%252F%252Flocalhost%252Ftestauthenti%252Fnode_modules%252Frestangular%252Fdist%252Frestangular.js%253A42%253A29)%250A%2520%2520%2520%2520at%2520new%2520%253Canonymous%253E%2520(http%253A%252F%252Flocalhost%252Ftestauthenti%252Fnode_modules%252Frestangular%252Fdist%252Frestangular.js%253A812%253A16)%250A%2520%2520%2520%2520at%2520Object.instantiate%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A44%253A458)%250A%2520%2520%2520%2520at%2520c%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A41%253A370)%250A%2520%2520%2520%2520at%2520Object.provider%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A41%253A312)%250A%2520%2520%2520%2520at%2520d%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A42%253A237)%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A42%253A358%250A%2520%2520%2520%2520at%2520p%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A8%253A7)%250A%2520%2520%2520%2520at%2520g%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A42%253A138)%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A42%253A322%0A%20%20%20%20at%20https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A7%3A76%0A%20%20%20%20at%20https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A43%3A70%0A%20%20%20%20at%20p%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A42%3A322%0A%20%20%20%20at%20p%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20gb%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A46%3A251)%0A%20%20%20%20at%20c%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A22%3A19)%0A%20%20%20%20at%20Uc%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A22%3A332)
and this is link error:
https://docs.angularjs.org/error/$injector/unpr?p0=RestangularProvider%20%3C-%20Restangular%20%3C-%20MainCtrl
code index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="styles/main.css"> -->
</head>
<body ng-app="angularApp">
<div class="container">
<div ng-include="'main.html" ng-controller="MainCtrl"></div>
<div ui-view></div>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
--> <script src="../node_modules/angular/angular.js"></script>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.js"></script>
-->
<script src="../node_modules/restangular/dist/restangular.js"></script>
<script src="../node_modules/lodash/lodash.js"></script>
<script src="app.js"></script>
<script src="main.js"></script>
</body>
</html>
code main.html:
<!—Displays error or success messages-->
<span>{{message}}</span><br><br>
<!—Login/logout form-->
<form ng-show="!isAuthenticated" ng-submit="submit()">
<label>Login Form:</label><br>
<input ng-model="user.username" type="text" name="user" placeholder="Username" disabled="true" />
<input ng-model="user.password" type="password" name="pass" placeholder="Password" disabled="true" />
<input type="submit" value="Login" />
</form>
<div ng-show="isAuthenticated">
<a ng-click="logout()" href="">Logout</a>
</div>
<div ui-view ng-show="isAuthenticated"></div>
<br><br>
<!—Displays contacts list-->
<h1 ng-show="isAuthenticated">Liste des Contacts</h1>
<article ng-repeat="contact in contacts" ng-show="isAuthenticated" id="{{ contact['#id'] }}" class="row marketing">
<h2>{{ contact.nom }}</h2>
<!—Displays contact phones list-->
<h3 ng-repeat="moyenComm in contact.moyensComm">Tél : {{ moyenComm.numero }}</h3>
</article><hr>
<!—Create contact form-->
<form name="createContactForm" ng-submit="createContact(createContactForm)" ng-show="isAuthenticated" class="row marketing">
<h2>Création d'un nouveau contact</h2>
<!—Displays error / success message on creating contact-->
<div ng-show="contactSuccess" class="alert alert-success" role="alert">Contact publié.</div>
<div ng-show="contactErrorTitle" class="alert alert-danger" role="alert">
<b>{{ contactErrorTitle }}</b><br>
{{ contactErrorDescription }}
</div>
<div class="form-group">
<input ng-model="newContact.nom" placeholder="Nom" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<!—Phone form-->
<form name="createPhoneForm" ng-submit="createPhone(createPhoneForm)" ng-show="isAuthenticated" class="row marketing">
<h2>Création d'un nouveau téléphone</h2>
<div ng-show="phoneSuccess" class="alert alert-success" role="alert">Téléphone publié.</div>
<div ng-show="phoneErrorTitle" class="alert alert-danger" role="alert">
<b>{{ phoneErrorTitle }}</b><br>
{{ phoneErrorDescription }}
</div>
<div class="form-group">
<input ng-model="newPhone.numero" placeholder="Numéro" class="form-control">
</div>
<div class="form-group">
<label for="contact">Contact</label>
<!—SelectBox de liste de contacts-->
<select ng-model="newPhone.contact" ng-options="contact['#id'] as contact.nom for contact in contacts" id="contact"></select>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
code app.js:
'use strict';
var app = angular
.module('angularApp', ['restangular'])
app.config(['RestangularProvider', function (RestangularProvider) {
// URL ENDPOINT TO SET HERE !!!
RestangularProvider.setBaseUrl('http://your_vhost/api');
RestangularProvider.setRestangularFields({
id: '#id'
});
RestangularProvider.setSelfLinkAbsoluteUrl(false);
RestangularProvider.addResponseInterceptor(function (data, operation) {
function populateHref(data) {
if (data['#id']) {
data.href = data['#id'].substring(1);
}
}
populateHref(data);
if ('getList' === operation) {
var collectionResponse = data['hydra:member'];
collectionResponse.metadata = {};
angular.forEach(data, function (value, key) {
if ('hydra:member' !== key) {
collectionResponse.metadata[key] = value;
}
});
angular.forEach(collectionResponse, function (value) {
populateHref(value);
});
return collectionResponse;
}
return data;
});
}])
;
code main.js:
'use strict';
var app = angular
.module('angularApp')
app.controller('MainCtrl', function ($scope, $http, $window, Restangular) {
// fosuser user
$scope.user = {username: 'johndoe', password: 'test'};
// var to display login success or related error
$scope.message = '';
// In my example, we got contacts and phones
var contactApi = Restangular.all('contacts');
var phoneApi = Restangular.all('telephones');
// This function is launched when page is loaded or after login
function loadContacts() {
// get Contacts
contactApi.getList().then(function (contacts) {
$scope.contacts = contacts;
});
// get Phones (throught abstrat CommunicationWays alias moyensComm)
phoneApi.getList().then(function (phone) {
$scope.phone = phone;
});
// some vars set to default values
$scope.newContact = {};
$scope.newPhone = {};
$scope.contactSuccess = false;
$scope.phoneSuccess = false;
$scope.contactErrorTitle = false;
$scope.contactErrorDescription = false;
$scope.phoneErrorTitle = false;
$scope.phoneErrorDescription = false;
// contactForm handling
$scope.createContact = function (form) {
contactApi.post($scope.newContact).then(function () {
// load contacts & phones when a contact is added
loadContacts();
// show success message
$scope.contactSuccess = true;
$scope.contactErrorTitle = false;
$scope.contactErrorDescription = false;
// re-init contact form
$scope.newContact = {};
form.$setPristine();
// manage error handling
}, function (response) {
$scope.contactSuccess = false;
$scope.contactErrorTitle = response.data['hydra:title'];
$scope.contactErrorDescription = response.data['hydra:description'];
});
};
// Exactly same thing as above, but for phones
$scope.createPhone = function (form) {
phoneApi.post($scope.newPhone).then(function () {
loadContacts();
$scope.phoneSuccess = true;
$scope.phoneErrorTitle = false;
$scope.phoneErrorDescription = false;
$scope.newPhone = {};
form.$setPristine();
}, function (response) {
$scope.phoneSuccess = false;
$scope.phoneErrorTitle = response.data['hydra:title'];
$scope.phoneErrorDescription = response.data['hydra:description'];
});
};
}
// if a token exists in sessionStorage, we are authenticated !
if ($window.sessionStorage.token) {
$scope.isAuthenticated = true;
loadContacts();
}
// login form management
$scope.submit = function() {
// login check url to get token
$http({
method: 'POST',
url: 'http://your_vhost/login_check',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: $.param($scope.user)
// with success, we store token to sessionStorage
}).success(function(data) {
$window.sessionStorage.token = data.token;
$scope.message = 'Successful Authentication!';
$scope.isAuthenticated = true;
// ... and we load data
loadContacts();
// with error(s), we update message
}).error(function() {
$scope.message = 'Error: Invalid credentials';
delete $window.sessionStorage.token;
$scope.isAuthenticated = false;
});
};
// logout management
$scope.logout = function () {
$scope.message = '';
$scope.isAuthenticated = false;
delete $window.sessionStorage.token;
};
// This factory intercepts every request and put token on headers
})
app.factory('authInterceptor', function($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
response: function (response) {
if (response.status === 401) {
// if 401 unauthenticated
}
return response || $q.when(response);
}
};
// call the factory ...
})
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
help me please for resolve this bug and thanks advanced
I think isUndefined is a function in underscore.js, which is a dependency of Restangular:
http://underscorejs.org/#isUndefined
Do you have underscore.js included in your assets?
How I can save images with laravel and angular js ?
are more inputs , but that work for me , are of type text
My index:
<div class="container" ng-app="todoApp" ng-controller="todoController">
<h1>Profile</h1>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<h4>Foto de perfil: </h4>
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type='File' name="photo" ng-model="todo.photo" class="image-upload"required/>
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="">Nombre del bar: </label>
<input type='text' ng-model="todo.name" class="form-control" required/>
</div>
<button class="btn btn-primary btn-block" ng-click="addTodo()">Guardar</button>
<i ng-show="loading" class="fa fa-spinner fa-spin"></i>
</div>
</div>
My route:
Route::get('admin/bar', 'BarsController#index');
Route::resource('/bar', 'BarController');
My model:
namespace App;
use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;
use Illuminate\Support\Facades\Input;
use Illuminate\Database\Eloquent\Model;
class bar extends Model
{
protected $fillable = array('name','photo', 'cover',
'description', 'phone', 'email','direction', );
public function setPhotoAttribute($photo)
{
$file = array('image' => Input::file('photo'));
$destinationPath = 'images/bar/profile';
$extension = Input::file('photo')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension;
$this->attributes['photo'] = $fileName;
Input::file('photo')->move($destinationPath, $fileName);
}
BarsController:
public function index()
{
return view ('bar.index');
}
BarController:
public function store() {
$todo = \Auth::user()->bars()->create(Request::all());
return $todo;
}
App.js ( Angular JS ):
var app = angular.module('todoApp', function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
// Todo Controller ,...
app.controller('todoController', function($scope, $http) {
$scope.todos = [];
$scope.loading = false;
$scope.init = function() {
$scope.loading = true;
$http.get('/bar').
success(function(data, status, headers, config) {
$scope.todos = data;
$scope.loading = false;
});
}
$scope.addTodo = function() {
$scope.loading = true;
$http.post('/bar', {
name: $scope.todo.name,
description: $scope.todo.description,
phone: $scope.todo.phone,
email: $scope.todo.email,
direction: $scope.todo.direction,
photo: $scope.todo.photo,
cover: $scope.todo.cover
}).success(function(data, status, headers, config) {
$scope.todos.push(data);
$scope.todo = '';
$scope.loading = false;
});
};
$scope.updateTodo = function(todo) {
$scope.loading = true;
$http.put('/bar' + todo.id, {
title: todo.title,
done: todo.done
}).success(function(data, status, headers, config) {
todo = data;
$scope.loading = false;
});;
};
$scope.deleteTodo = function(index) {
$scope.loading = true;
var todo = $scope.todos[index];
$http.delete('/bar' + todo.id)
.success(function() {
$scope.todos.splice(index, 1);
$scope.loading = false;
});;
};
$scope.init();
});
I am using below code to upload image try this, I hope it works for you too.
<-- Front end file input -->
<input type="file" name="file" onchange="angular.element(this).scope().uploadavtar(this.files)"/>
<-- Angular Controller's File -->
$scope.uploadavtar = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post("/uploadavtar", fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).then(function successCallback(response) {
alert(response);
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
alert(response);
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
<-- In Route File -->
Route::post('/uploadavtar', 'UsersController#uploadavtar');
<-- In UsersController -->
public function uploadavtar(Request $request){
$user = JWTAuth::parseToken()->authenticate();
$user_id = $user->id;
$user_name = $user->first_name." ".$user->last_name;
$file = array('image' => Input::file('file'));
// setting up rules
$rules = array('image' => 'required',); //mimes:jpeg,bmp,png and for max size max:10000
// doing the validation, passing post data, rules and the messages
$validator = Validator::make($file, $rules);
if ($validator->fails()) {
// send back to the page with the input data and errors
return "validation failed";
}else {
// checking file is valid.
if (Input::file('file')->isValid()) {
$destinationPath = 'assets/img'; // upload path
$extension = Input::file('file')->getClientOriginalExtension(); // getting image extension
$fileName = rand(11111,99999).'.'.$extension; // renameing image
Input::file('file')->move($destinationPath, $user_name."_$user_id".".jpeg"); // uploading file to given path
// sending back with message
return 'Upload successfully';
}
else {
// sending back with error message.
return 'uploaded file is not valid';
}
}
}
I'm working on building a little app that accepts input from a form (the input being a name) and then goes on to POST the name to a mock webservice using $httpBackend. After the POST I then do a GET also from a mock webservice using $httpBackend that then gets the name/variable that was set with the POST. After getting it from the service a simple greeting is constructed and displayed back at the client.
However, currently when the data gets displayed now back to the client it reads "Hello undefined!" When it should be reading "Hello [whatever name you inputed] !". I used Yeoman to do my app scaffolding so I hope everyone will be able to understand my file and directory structure.
My app.js:
'use strict';
angular
.module('sayHiApp', [
'ngCookies',
'ngMockE2E',
'ngResource',
'ngSanitize',
'ngRoute'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
})
.run(function($httpBackend) {
var name = 'Default Name';
$httpBackend.whenPOST('/name').respond(function(method, url, data) {
//name = angular.fromJson(data);
name = data;
return [200, name, {}];
});
$httpBackend.whenGET('/name').respond(name);
// Tell httpBackend to ignore GET requests to our templates
$httpBackend.whenGET(/\.html$/).passThrough();
});
My main.js:
'use strict';
angular.module('sayHiApp')
.controller('MainCtrl', function ($scope, $http) {
// Accepts form input
$scope.submit = function() {
// POSTS data to webservice
setName($scope.input);
// GET data from webservice
var name = getName();
// Construct greeting
$scope.greeting = 'Hello ' + name + ' !';
};
function setName (dataToPost) {
$http.post('/name', dataToPost).
success(function(data) {
$scope.error = false;
return data;
}).
error(function(data) {
$scope.error = true;
return data;
});
}
// GET name from webservice
function getName () {
$http.get('/name').
success(function(data) {
$scope.error = false;
return data;
}).
error(function(data) {
$scope.error = true;
return data;
});
}
});
My main.html:
<div class="row text-center">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<img src="../images/SayHi.png" class="logo" />
</div>
</div>
<div class="row text-center">
<div class="col-xs-10 col-xs-offset-1 col-md-4 col-md-offset-4">
<form role="form" name="greeting-form" ng-Submit="submit()">
<input type="text" class="form-control input-field" name="name-field" placeholder="Your Name" ng-model="input">
<button type="submit" class="btn btn-default button">Greet Me!</button>
</form>
</div>
</div>
<div class="row text-center">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<p class="greeting">{{greeting}}</p>
</div>
</div>
At the moment your getName() method returns nothing. Also you cant just call getName() and expect the result to be available immediately after the function call since $http.get() runs asynchronously.
You should try something like this:
function getName () {
//return the Promise
return $http.get('/name').success(function(data) {
$scope.error = false;
return data;
}).error(function(data) {
$scope.error = true;
return data;
});
}
$scope.submit = function() {
setName($scope.input);
//wait for the Promise to be resolved and then update the view
getName().then(function(name) {
$scope.greeting = 'Hello ' + name + ' !';
});
};
By the way you should put getName(), setName() into a service.
You can't return a regular variable from an async call because by the time this success block is excuted the function already finished it's iteration.
You need to return a promise object (as a guide line, and preffered do it from a service).
I won't fix your code but I'll share the necessary tool with you - Promises.
Following angular's doc for $q and $http you can build yourself a template for async calls handling.
The template should be something like that:
angular.module('mymodule').factory('MyAsyncService', function($q, http) {
var service = {
getNames: function() {
var params ={};
var deferObject = $q.defer();
params.nameId = 1;
$http.get('/names', params).success(function(data) {
deferObject.resolve(data)
}).error(function(error) {
deferObject.reject(error)
});
return $q.promise;
}
}
});
angular.module('mymodule').controller('MyGettingNameCtrl', ['$scope', 'MyAsyncService', function ($scope, MyAsyncService) {
$scope.getName = function() {
MyAsyncService.getName().then(function(data) {
//do something with name
}, function(error) {
//Error
})
}
}]);
So I'm running into this problem where I'm using ngView and I have a navigation bar that is static throughout like so:
<div ng-include="'views/nav.html'" ng-controller="NavCtrl"></div>
<div class="container-fluid" ng-view=""></div>
This nav.html, the navigation bar, displays a certain set of functions (Login, Register) if the user is logged out (using ng-show) and other menu options if the user is logged in. Because of the heavy use of current user, I've put this information in the $rootScope like this: $rootScope.currentUser - returns user object, and $rootScope.signedIn - return boolean.
Basically, I want to delay the navbar from loading until $rootScope.signedIn is loaded and either true or false, and $rootScope.currentUser is an object or undefined.
I've tried messing around with creating promises in my app.config routes, but I'm not sure how I can return a promise to the permanent view state.
Any help is appreciated.
Edit:
Here is the service in which I broadcast my login. This fires anytime a user is authenticated/logged in or anytime they logout:
var authClient = new FirebaseSimpleLogin(refDownload, function(error, user) {
if (error) {
incorrectLogin(error.code);
}
if (user) {
// user authenticated
$rootScope.$broadcast('login');
correctLogin(user.id);
} else {
// user is logged out
$rootScope.$broadcast('logout');
}
});
This service is injected into the NavCtrl controller in the following way:
$scope.isHidden = true;
$scope.$on('login', function() {
console.log('login broadcast');
$scope.isHidden = false;
});
$scope.$on('logout', function() {
console.log('broadcast logout');
$scope.isHidden = true;
});
The template for this controller is nav.html that looks like this:
<div class="col-xs-4 centered" id="nav-hover" ng-show="isHidden">
<ul class="nav navbar-nav">
<li id="nav-login"><a ng-href="#/login"><span class="glyphicon glyphicon-log-in"> Login</span></a></li>
</ul>
</div>
<div class="col-xs-4 centered" id="nav-hover" ng-show="isHidden">
<ul class="nav navbar-nav">
<li id="nav-login"><a ng-href="#/register"><span class="glyphicon glyphicon-edit"> Register</span></a></li>
</ul>
</div>
<div class="col-xs-2 centered" id="nav-hover">
<ul class="nav navbar-nav" ng-hide="isHidden">
<li ng-class="{{ chatCat.active }}"><a ng-href="{{ chatCat.url }}"><span class="{{ chatCat.icon }}"></span></a></li>
</ul>
</div>
Again, this view is bound to NavCtrl. When logging users in, I use AuthCtrl as follows:
$scope.login = function() {
if ($scope.user !== undefined) {
Auth.login($scope.user);
$location.path('/dexter');
} else {
console.log('nothing entered');
}
};
When I try to login, the nav view does not update with the new values, although the broadcast is fired from the service with 'logged in'.
Auth service:
'use strict';
app.factory('Auth',
function($rootScope, $location, $firebase, $firebaseSimpleLogin, firebaseUrl) {
var refDownload = new Firebase(firebaseUrl + 'housemates');
var sync = $firebase(refDownload);
var ref = sync.$asObject();
var authClient = new FirebaseSimpleLogin(refDownload, function(error, user) {
if (error) {
incorrectLogin(error.code);
}
if (user) {
// 1
// user authenticated
correctLogin(user.id);
} else {
// user is logged out
// $rootScope.signedIn = false;
}
});
var Auth = {
housemates: ref,
changeColor: function(color) {
var id = $rootScope.currentUser.id.toString();
refDownload.child(id).update({ color: color });
$rootScope.currentUser.color = color;
},
create: function(authUser, usr) {
refDownload.child(authUser.id).set({
initials: usr.initials,
email: authUser.email,
password: usr.password,
color: 'Blue',
id: authUser.id,
uid: authUser.uid,
rememberMe: true,
});
},
// 3
findById: function(id) {
refDownload.on('value', function(snapshot) {
var userObject = snapshot.val();
// 4 - sets currentUser
//$rootScope.currentUser = userObject[id];
var currentUser = userObject[id];
Auth.setUser(currentUser);
// $rootScope.signedIn = true;
}, function (error) {
console.log(error);
});
},
login: function(user) {
authClient.login('password', {
email: user.email,
password: user.password,
rememberMe: true
});
},
logout: function() {
delete $rootScope.currentUser;
delete $rootScope.signedIn;
delete $rootScope.error;
return authClient.logout();
},
register: function(user) {
var userSimple = user;
authClient.createUser(user.email, user.password, function(error, user) {
if(!error) {
var userComplex = user;
Auth.login(userSimple);
Auth.create(userComplex, userSimple);
return user;
} else {
console.log(error);
}
});
},
setUser: function(aUser) {
console.log('setuser ran');
$rootScope.currentUser = aUser;
console.log('setUser: ' + $rootScope.currentUser);
},
isLoggedIn: function() {
console.log($rootScope.currentUser);
return ($rootScope.currentUser) ? $rootScope.currentUser : false;
},
};
// 2
function correctLogin(id) {
Auth.findById(id);
}
function incorrectLogin(error) {
alert(error);
$rootScope.error = error;
}
return Auth;
});
With a bit of $rootScope.$broadcast and ng-hide on the menu, this could be easily accomplished. See this plunker
The html:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="https://code.angularjs.org/1.2.25/angular.js" data-semver="1.2.25"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-include="'nav.html'" ng-controller="NavCtrl" ng-hide="isHidden"></div>
<button class="btn" ng-click="login()">Login</button>
<button class="btn" ng-click="logout()">Logout</button>
</body>
</html>
The javascript:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $rootScope) {
$scope.login = function() {
$rootScope.$broadcast("login");
}
$scope.logout = function() {
$rootScope.$broadcast("logout");
}
});
app.controller('NavCtrl', function($scope) {
$scope.isHidden = true;
$scope.$on('login', function() {
console.log("logged in");
$scope.isHidden = false;
});
$scope.$on('logout', function() {
console.log("logged out");
$scope.isHidden = true;
});
});
OK, if the way i suggested isn't working for you, here is a second possible solution (plunker)
The base idea is to have a service (in this case a factory) in which you set the logged in user name and then in the nav controller use $watch to watch changes to the authentication status in the service. And the code:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="https://code.angularjs.org/1.2.25/angular.js" data-semver="1.2.25"></script>
<script src="app.js"></script>
<script src="Auth.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-include="'nav.html'" ng-controller="NavCtrl" ng-hide="isHidden"></div>
<button class="btn" ng-click="login()">Login</button>
<button class="btn" ng-click="logout()">Logout</button>
</body>
</html>
The javascript:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $rootScope, Auth) {
$scope.login = function() {
var user = "iris"
Auth.setUser(user);
}
$scope.logout = function() {
Auth.setUser(null);
}
});
app.controller('NavCtrl', function($scope, Auth) {
$scope.isHidden = true;
$scope.$watch(Auth.isLoggedIn, function (value, oldValue) {
console.log("authentication changed");
if(!value && oldValue) {
console.log("logged out");
$scope.isHidden = true;
}
if(value) {
console.log("logged in");
$scope.isHidden = false;
}
}, true);
});
and the service:
app.factory('Auth', function() {
var user;
return {
setUser: function(aUser) {
user = aUser;
},
isLoggedIn: function() {
console.log(user);
return (user) ? user : false;
}
}
})
#zszep $broadcast answer solved the problem with one caveat. It was necessary to add $scope.$apply() following each of the $scope.isHidden commands in NavCtrl. This forced a page refresh of sorts and the Nav view updated.