Laravel and Angular js file upload - javascript

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';
}
}
}

Related

can not add data in sql server database in angularjs?

I Have simple app in Angularjs and I have little experience in Angularjs.
my question is I can add data in database . I think I have no errors that prevent me from adding that data.
There no errors displayed but the data not send correctly
GoverController
public ActionResult Index(Governorate gov)
{
string message = "";
if (ModelState.IsValid)
{
using (DoctorEntities dc = new Models.DoctorEntities())
{
dc.Governorates .Add(gov);
dc.SaveChanges();
message = "تم اضافة المحافظة";
}
}
else
{
message = "خطا";
}
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
gov.js
(function () {
angular.module('MyApp', [])
.controller('AdminController', function ($scope, RegisterService) {
$scope.submitText = "save";
$scope.submitted = false;
$scope.message = '';
$scope.isFormValid = false;
$scope.gov = {
GovernorateName: ''
};
$scope.$watch('f1.$valid', function (newValue) {
$scope.isFormValid = newValue;
});
$scope.SaveDate = function (data) {
if (submitText == "save") {
$scope.submitted = true;
$scope.message = '';
}
if ($scope.isFormValid==false){
$scope.submitText = "please wait....";
$scope.gov = data;
RegisterService.SaveFoemData($scope.gov).then(function (d) {
alert(d);
if (d == 'success') {clearform(); }$scope.submitText='save';
} );
}
else{
$scope.message='please fill required data';
}
};
function clearform(){
$scope.gov=null;
$scope.f1.$setPristine();
$scope.submitted=false;
}})
.factory('RegisterService', function ($http,$q) {
var fac = {};
fac.SaveFoemData = function (data) {
var defer = $q.defer();
$http({
url: '/Gover/Index',
method: 'get',
data: JSON.stringify(data),
headers: {'content-type':'application/json'}
}).success(function (d) {
defer.resolve(d);
}).error(function (e) {
defer.reject(e);
});
return defer.promise();
}
return fac;
});
})();
AddGov.cshtml
#{
ViewBag.Title = "AddGov";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>AddGov</h2>
<div ng-controller="AdminController">
<form novalidate name="f1" ng-submit="SaveData(gov)">
{{message}}
<table>
<tr>
<td>
<input type="text" ng-model="gov.GovernorateName" name="GovernorateName" ng-class="submitted?'ng-dirty':''" required autofocus />
</td>
</tr>
<tr>
<td><input type="submit" value="{{submitText}}" /></td>
</tr>
</table>
</form>
</div>
#section scripts{
<script src="~/Scripts/MyProject/gov.js"></script>
}
i tried to find solution to this question

Failed to instantiate module angularApp due to

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 to route CodeIgniter with Angular.js? [duplicate]

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>

JSON request with Angular Displays an Empty Response

I believe Angular is loading the page before it receives all the information from JSONP. If I refresh the page a couple of times I do get the information to display; however, it is not constant. My code is almost the same as the code I am using on my projects page which does not have the same issue.
HTML:
<div class="container">
<div class="row push-top" ng-show="user">
<div class="col-xs-10 col-xs-offset-1 col-sm-10 col-sm-offset-1 col-md-10 col-md-offset-1">
<div class="well well-sm">
<div class="row">
<div class="col-sm-3 col-md-2">
<img ng-src="[[ user.images.138 ]]" alt="" class="img-rounded img-responsive" />
</div>
<div class="col-sm-7 col-md-8">
<h4 ng-bind="user.display_name"></h4>
<h5 ng-bind="user.occupation"></h5>
<i class="fa fa-map-marker"></i>
<cite title="[[ user.city ]], [[ user.country ]]">[[ user.city ]], [[ user.country ]]</cite>
<br>
<strong ng-bind="user.stats.followers"></strong> Followers, <strong ng-bind="user.stats.following"></strong> Following
<hr>
<p style="margin-top:10px;" ng-bind="user.sections['About Me']"></p>
</div>
</div>
</div>
</div>
</div>
</div>
JavaScipt:
'use strict';
angular.module('angularApp')
.controller('AboutCtrl', function ($scope, $window, Behance) {
$scope.loading = true;
Behance.getUser('zachjanice').then(function (user) {
$scope.user = user;
$scope.loading = false;
}, function (error) {
console.log(error);
$scope.loading = false;
$scope.user = null;
});
$scope.gotoUrl = function (url) {
$window.location.href = url;
};
});
You can see the page in question at: http://zachjanice.com/index.html#/about. Thanks in Advance.
As requested here is the behance service:
'use strict';
angular.module('angularApp')
.factory('Behance', function ($http, $q, localStorageService, BEHANCE_CLIENT_ID) {
// Should be called to refresh data (for testing purposes)
// localStorageService.clearAll();
// Public API
return {
// Get a list of projects
getProjects: function (config) {
var pageNum = 1;
if (angular.isObject(config) && angular.isDefined(config.page)) {
pageNum = config.page;
}
var _projects = $q.defer(),
_storedProjects = localStorageService.get('Projects_Page_');
if (_storedProjects !== null) {
_projects.resolve(_storedProjects);
} else {
$http.jsonp('https://www.behance.net/v2/users/zachjanice/projects', {
params: {
'client_id': BEHANCE_CLIENT_ID,
'callback': 'JSON_CALLBACK',
'page': pageNum
}
})
.then(function (response) {
if (response.data.http_code === 200 && response.data.projects.length > 0) {
// console.log('getting page', _page);
_projects.resolve(response.data.projects);
localStorageService.add('Projects_Page_' + pageNum, response.data.projects);
}
});
}
return _projects.promise;
},
// Get project with id
getProject: function (id) {
var _project = $q.defer();
$http.jsonp('https://www.behance.net/v2/projects/' + id, {
params: {
'client_id': BEHANCE_CLIENT_ID,
'callback': 'JSON_CALLBACK'
},
cache: true
}).success(function (data){
_project.resolve(data.project);
});
return _project.promise;
},
// Get project with id
getUser: function (username) {
var _user = $q.defer();
$http.jsonp('https://www.behance.net/v2/users/' + username, {
params: {
'client_id': BEHANCE_CLIENT_ID,
'callback': 'JSON_CALLBACK'
},
cache: true
}).success(function (data){
_user.resolve(data.user);
});
return _user.promise;
}
};
});
Anthony Chu supplied no support, so I found the answer myself. The issue was not the Behance Service, but the Projects Controller like I had originally stated.
I changed $scope.loading under the call for the service from false to true. Works every time.

AngularJS Uploading An Image With ng-upload

I am trying to upload a file in AngularJS using ng-upload but I am running into issues. My html looks like this:
<div class="create-article" ng-controller="PostCreateCtrl">
<form ng-upload method="post" enctype="multipart/form-data" action="/write" >
<fieldset>
<label>Category</label>
<select name="category_id" class="">
<option value="0">Select A Category</option>
<?php foreach($categories as $category): ?>
<option value="<?= $category -> category_id; ?>"><?= $category -> category_name; ?></option>
<?php endforeach; ?>
</select>
<label>Title</label>
<input type="text" class="title span5" name="post_title"
placeholder="A catchy title here..."
value="<?= $post -> post_title; ?>" />
<label>Attach Image</label>
<input type="file" name="post_image" />
<a href='javascript:void(0)' class="upload-submit: uploadPostImage(contents, completed)" >Crop Image</a>
<label>Body</label>
<div id="container">
<textarea id="mytextarea" wrap="off" name="post_content" class="span7" placeholder="Content..."><?= $post -> post_content; ?></textarea>
</div>
<div style='clear:both;'></div>
<label>Preview</label>
<div id='textarea-preview'></div>
</fieldset>
<div class="span7" style="margin: 0;">
<input type="submit" class="btn btn-success" value="Create Post" />
<input type="submit" class="btn btn-warning pull-right draft" value="Save as Draft" />
</div>
</form>
</div>
And my js controller looks like this:
ClabborApp.controller("PostCreateCtrl", ['$scope', 'PostModel',
function($scope, PostModel) {
$scope.uploadPostImage = function(contents, completed) {
console.log(completed);
alert(contents);
}
}]);
The problem I am facing is when the crop image is hit and it executes uploadPostImage, it uploads the entire form. Not desired behavior but I can make it work. The big problem is in the js the function uploadPostImage 'contents' parameters is always undefined, even when the 'completed' parameter comes back as true.
The goal is to only upload an image for cropping. What am I doing wrong in this process?
There's little-no documentation on angular for uploading files. A lot of solutions require custom directives other dependencies (jquery in primis... just to upload a file...). After many tries I've found this with just angularjs (tested on v.1.0.6)
html
<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>
Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.
controller
$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post(uploadUrl, fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success( ...all right!... ).error( ..damn!... );
};
The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.
You can try ng-file-upload angularjs plugin (instead of ng-upload).
It's fairly easy to setup and deal with angularjs specifics. It also supports progress, cancel, drag and drop and is cross browser.
html
<!-- Note: MUST BE PLACED BEFORE angular.js-->
<script src="ng-file-upload-shim.min.js"></script>
<script src="angular.min.js"></script>
<script src="ng-file-upload.min.js"></script>
<div ng-controller="MyCtrl">
<input type="file" ngf-select="onFileSelect($files)" multiple>
</div>
JS:
//inject angular file upload directives and service.
angular.module('myApp', ['ngFileUpload']);
var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
$scope.upload = $upload.upload({
url: 'server/upload/url', //upload.php script, node.js route, or servlet url
data: {myObj: $scope.myModelObj},
file: file,
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).then(function(response) {
var data = response.data;
// file is uploaded successfully
console.log(data);
});
}
};
}];
In my case above mentioned methods work fine with php but when i try to upload files with these methods in node.js then i have some problem.
So instead of using $http({..,..,...}) use the normal jquery ajax.
For select file use this
<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this)"/>
And in controller
$scope.uploadFile = function(element) {
var data = new FormData();
data.append('file', $(element)[0].files[0]);
jQuery.ajax({
url: 'brand/upload',
type:'post',
data: data,
contentType: false,
processData: false,
success: function(response) {
console.log(response);
},
error: function(jqXHR, textStatus, errorMessage) {
alert('Error uploading: ' + errorMessage);
}
});
};
var app = angular.module('plunkr', [])
app.controller('UploadController', function($scope, fileReader) {
$scope.imageSrc = "";
$scope.$on("fileProgress", function(e, progress) {
$scope.progress = progress.loaded / progress.total;
});
});
app.directive("ngFileSelect", function(fileReader, $timeout) {
return {
scope: {
ngModel: '='
},
link: function($scope, el) {
function getFile(file) {
fileReader.readAsDataUrl(file, $scope)
.then(function(result) {
$timeout(function() {
$scope.ngModel = result;
});
});
}
el.bind("change", function(e) {
var file = (e.srcElement || e.target).files[0];
getFile(file);
});
}
};
});
app.factory("fileReader", function($q, $log) {
var onLoad = function(reader, deferred, scope) {
return function() {
scope.$apply(function() {
deferred.resolve(reader.result);
});
};
};
var onError = function(reader, deferred, scope) {
return function() {
scope.$apply(function() {
deferred.reject(reader.result);
});
};
};
var onProgress = function(reader, scope) {
return function(event) {
scope.$broadcast("fileProgress", {
total: event.total,
loaded: event.loaded
});
};
};
var getReader = function(deferred, scope) {
var reader = new FileReader();
reader.onload = onLoad(reader, deferred, scope);
reader.onerror = onError(reader, deferred, scope);
reader.onprogress = onProgress(reader, scope);
return reader;
};
var readAsDataURL = function(file, scope) {
var deferred = $q.defer();
var reader = getReader(deferred, scope);
reader.readAsDataURL(file);
return deferred.promise;
};
return {
readAsDataUrl: readAsDataURL
};
});
*************** CSS ****************
img{width:200px; height:200px;}
************** HTML ****************
<div ng-app="app">
<div ng-controller="UploadController ">
<form>
<input type="file" ng-file-select="onFileSelect($files)" ng-model="imageSrc">
<input type="file" ng-file-select="onFileSelect($files)" ng-model="imageSrc2">
<!-- <input type="file" ng-file-select="onFileSelect($files)" multiple> -->
</form>
<img ng-src="{{imageSrc}}" />
<img ng-src="{{imageSrc2}}" />
</div>
</div>

Categories

Resources