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>
Related
I am new to AngularJs. I am trying to upload a image file (.bmp,.jpg, etc) along with its label through Jax-RS post rest API but my control in not going into java post api from my angularjs controller.
While debugging the control is not coming into java file. Could you please help to understand what si wrong in my code.
myfile.html
Label of File: <input type="text" name="iconlabel" data-ng-model="imporLabelName"><br>
Import a File: <input type="file" id="myFile" name="myfile" data-file-model="myfile"><br>
<button type="button" class="btn btn-primary pull-right" data-ng-click="uploadfile();">Submit
</button>
myFileController
define([ '{angular}/angular' ], function(angular) {
var module = angular.module('myFile', [ 'ngResource', 'colorpicker-dr' ]);
module.controller('myFileController', [ '$scope', '$sce', '$http', '$location', '$window', 'w20MessageService'
,function($scope, $sce, $http, $location, $window, w20MessageService) {
var config = {
headers: {
"Content-Type": undefined,
}
};
/*** Modale for MyFile **/
$scope.openMyFile = function() {
$("#myfile").modal("show");
};
$scope.uploadfile = function() {
$scope.file = document.getElementById('myFile').files[0];
alert('LabelName = '+$scope.imporLabelName);
var formData = new $window.FormData();
formData.append("label", $scope.imporLabelName);
formData.append("file", $scope.file);
alert('File = '+$scope.file);
var url = "uploadfile/label="+$scope.imporLabelName;
alert("URL = "+url);
$http.post(url,$scope.formData,config).success(function(response) {
$scope.result = "SUCCESS";
}).error(function(response, status) {
if (status === 400) {
w20MessageService.addMessageErreur(data.message, "msgGererParam");
} else {
w20MessageService.addMessageErreur("eox.message.error.load.traitement", "msgGererParam");
}
});
$("#myfile").modal("hide");
};
} ]);
return {
angularModules : [ 'digitalJes' ]
};
});
java api code
#POST
#Path("/uploadfile/{label}")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.TEXT_PLAIN)
public Response uploadFile(#PathParam("label") String label, #FormDataParam("file") InputStream fileInputStream,
#FormDataParam("file") FormDataContentDisposition fileInputDetails) {
CacheControl cc = new CacheControl();
cc.setNoCache(true);
return Response.ok(uploadFileUtil.uploadFile(label, fileInputStream, fileInputDetails)).cacheControl(cc).build();
}
Error Code and Error Message
HTTP Status 400 – Bad Request
The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
#FormDataParam("file") InputStream fileInputStream,
#FormDataParam("file") FormDataContentDisposition fileInputDetails
Seems both of the fileInputStream and fileInputDetails variables are initializing from file parameter. Also in html the field is
...
Import a File: <input type="file" id="myFile" name="myfile" data-file-model="myfile"><br>
Here id="myFile" and name="myfile" and you are receiving those as "#FormDataParam("file")".
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?
I am a newbie of angularjs using version 1.6.4. I am using this module leon/angular-upload for upload functionality, minify version. On successful upload request, server return json object of uploaded file information on onSuccess(response) function as you can see in my user-registration.template.html file. Now i need to take this json object to my controller so that i can save this information in my database. Below is the few lines of my code.
user-registration.template.html:
<form role="form">
<div class="form-group float-label-control">
<label>Name</label>
<input type="text" placeholder="Name" class="form-control" ng-model="model.user.name">
</div>
<!-- leon/angular-upload -->
<div upload-button
url="/user_uploads"
on-success="onSuccess(response)"
on-error="onError(response)">Upload</div>
<div class="text-center">
<button type="button" class="btn btn-default" ng-click="model.save(model.user)">Save</button>
</div>
</form>
My component "user-registration.component.js":
(function(){
"use strict";
var module = angular.module(__appName);
function saveUser(user, $http){
var url = user.id > 0 ? __apiRoot + "/users/" + user.id : __apiRoot + "/users";
var dataObj = {
payload: JSON.stringify(user),
_method: "PUT"
}
return $http.post(url, dataObj);
}
function controller($http){
var model = this;
model.user = null;
model.save = function(user){
console.log(JSON.stringify(user));
saveUser(user, $http).then(function(response){
alert(response.data.msg);
});
}
}
module.component("userRegistration", {
templateUrl: "components/user-registration/user-registration.template.html",
bindings: {
value: "<"
},
controllerAs: "model",
controller: ["$http", controller]
});
}());
Try to put your server response data to rootScope model for Exempel :
$rootScope.serveResponse = response ;
and with this rootScope you can share your variable data between controller
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';
}
}
}
This is my first project on angular. I have created a directive. I am not able to insert the value which I am fetching from an object served by a RESTful API. The object as shown in the console is like this,
Below are the necessary files,
knob.js(directive)
angular.module('knob', [])
.directive('knob', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.knob({
fgColor: attrs.fgColor
});
}
}
})
dashboard.js(controller)
myApp.controller('DashController', function($scope, $http, $cookies, $cookieStore) {
$http({
url: site + '/company/dashboard',
method: "GET",
transformRequest: encodeurl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data) {
console.log(data); //data has the object that i want to use
$scope.dash = data.count;
}).error(function(res) {
console.log(res);
});
});
dahboard.html(view)
<li>
<div class="knob_contain">
<h4 class="knobs_title">Deals Left This Month</h4>
<input type="text" value="{{dash.profile}}" knob class="dial dialIndex">
</div>
</li>
I want the count.profile value to be bound to input type where I am using my knob. I will give you more files if you need.
The better way is assign a model to text box like,
<input type="text" ng-model="dash.profile" knob class="dial dialIndex">
You can change your code look like
AngulaJs code
var app = angular.module('app', []);
app.service('yourService', function ($http) {
this.getUser = function () {
return $http({ url: site + '/company/dashboard',
method: "GET",
transformRequest: encodeurl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data) {
console.log(data); //data has the object that i want to use
$scope.dash = data;
}).error(function(res) {
console.log(res);
});
};
});
app.controller('DashController', function($scope, $http, $cookies, $cookieStore, yourService) {
$scope.dash =null;
yourService.getUser().then(function (resp) {
if (resp.data !== undefined) {
console.log(data); //data has the object that i want to use
$scope.dash = data.count;
}
})
.error(function(res){
console.log(res);
});
});
app.directive('knob', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.knob({
fgColor: attrs.fgColor
});
}
}
});
HTML code sample
< li>
<div class="knob_contain">
<h4 class="knobs_title">Deals Left This Month</h4>
<input type="text" value="{{dash.profile}}" knob class="dial dialIndex">
</div>
</li>
You need to make a small change in your dashboard.html page.
For input elements, the ng-model property sets the value of the input box. For details see the docs on input[text]
So instead of using
<input type="text" value="{{dash.profile}}" knob class="dial dialIndex">
use
<input type="text" ng-model="dash.profile" knob class="dial dialIndex">