File Upload in Angular and Laravel API - angularjs

How can I stop getting 401 errors when I upload an image?
API
public function upload_office_logo(Request $request, $header_image)
{
$header_image = $request['header_image'];
$profileImageSaveAsName = time().".".$header_image->getClientOriginalExtension();
Storage::put('public/header_image/'.$profileImageSaveAsName,
file_get_contents($header_image));
return $header_image;
}
Angular UI
saveButton()
{
let logo = this.officeModel.header_image;
var filename = logo.split("\\", 3);
console.log(filename[2]);
this.officeModel.login_pw = "password123";
this.officeService.addOfficeLogo(filename[2]).subscribe(data => {
});
this.officeModel.header_image = filename[2];
this.officeService.addOffice(this.officeModel).subscribe(data => {
this.toastr.success('Added Successfuly', 'Success');
this.router.navigate(['/dashboard-manage/office']);
});
}
HTML
<div class="flex-input-grp">
<div class="required-label">{{ setLabel("Office Logo") }}</div>
<span class="label label-danger">{{ setLabel("Required") }}</span>
<div class="inp-container">
<input type="file" #fileUpload id="header_image" name="header_image" accept="image/*"
class="inp" [(ngModel)]="officeModel.header_image" [ngModelOptions]="{standalone: true}">
</div>
</div>

Related

AngularJS toggle ng source value on click

I need some help about toggling ng-src between for example: image.jpg and image-active.jpg, but I have some issues because I need to active that with AngularJS.
This is the scenario: I called an API data from swagger and use ng-repeat to display images in html.
HTML
<div class="input-group interests-list">
<div class="checkbox" ng-repeat="interest in interests">
<label>
<div class="interest-icon">
<img src="{{interest.iconUrl}}" ng-click="changeImage()">
</div>
<input style="display: none;" type="checkbox" value="{{interest.name}}">
{{interest.name}}
</label>
</div>
</div>
Service
this.getInterests = function () {
var deferred = $q.defer();
var req = {
method: 'get',
url: 'http://customdealwebapi20180125110644.azurewebsites.net/api/Interests'
}
$http(req).then(function (response) {
deferred.resolve(response.data);
}, function (err) {
console.log(err)
});
return deferred.promise;
}
Controller
TestService.getInterests().then(function (data) {
$scope.interests = data;
});
and everything works fine
Now I want to achieve when someone click on the image, ng-src should be changed to image-active.jpg, and on the next click image should be changed to default value (image.jpg)
I know how to achieve through jQuery, like this
$(".interests-list .checkbox label input[type='checkbox']").change(function () {
var selectedIcon = $(this).val();
if (this.checked) {
console.log($(this).prev())
$(this).prev().find("img").attr("src", "assets/img/home/icons/" + selectedIcon + "-active.png");
} else {
$(this).prev().find("img").attr("src", "assets/img/home/icons/" + selectedIcon + ".png");
}
});
Thank you
You can either use ng-show
<div class="checkbox" ng-repeat="interest in interests" ng-init="interest.active = false">
<label>
<div class="interest-icon">
<img ng-show="interest.active == true" src="active.png" ng-click="interest.active = !interest.active">
<img ng-show="interest.active == false" src="other.png" ng-click="interest.active = !interest.active">
</div>
</label>
</div>
or you can pass interest to your click function and set image src in your controller
<img src="{{interest.iconUrl}}" ng-click="changeImage(interest)">
$scope.changeImage = function(interest){
if(checked)
interest.iconUrl = "active.png";
else
interest.iconUrl = "other.png";
}

ng-show not watching variable change

I have a progress bar I want to show after I click a button.
I set my variable to true on click, yet it's not working.
The ng-show in question is on the bottom of the html, and the button i click is on a different html page but i didn't include because it uses the successOnClick function in this same controller. I console logged the isEmailing variable inside the onclick and it is assigned true. Doesn't work for ng-if either
What gives?
module.exports = app => {
app.controller('ContactController', ($scope, $http) => {
$scope.isEmailing = false;
$scope.email = (e) => {
$scope.isEmailing = true;
const requestBody = {};
const id = e.target.id;
requestBody.name = document.getElementById(`${id}-name`).value;
requestBody.email = document.getElementById(`${id}-email`).value;
requestBody.subject = document.getElementById(`${id}-subject`).value;
requestBody.body = document.getElementById(`${id}-body`).value;
$http.post('/email', JSON.stringify(requestBody), {
'Content-Type': 'application/json'
})
.then(res => {
console.log('Success!');
document.getElementById(`${id}-name`).value = '';
document.getElementById(`${id}-email`).value = '';
document.getElementById(`${id}-subject`).value = '';
document.getElementById(`${id}-body`).value = '';
$scope.isEmailing = false;
})
.catch(err => {
console.log('Error!');
$scope.isEmailing = false;
})
}
$scope.successOnClick = () => {
$scope.isEmailing = true;
}
})
}
<footer class="footer" ng-controller="ContactController">
<div class="footer__block social-media-container">
<div class="social-media">
<img src="http://i.imgur.com/bVqv5Kk.png" alt="fb-icon">
<img src="http://i.imgur.com/sJWiCHV.png" alt="twitter-icon">
<img src="http://i.imgur.com/o7yTVyL.png" alt="insta-icon">
</div>
</div>
<div class="footer__block">
<form class="footer__form" ng-submit="email($event)" id="footer">
<textarea placeholder="Message" id="footer-body" required></textarea>
<input type="text" placeholder="Name" id="footer-name" required>
<input type="email" placeholder="Email" id="footer-email" required>
<input type="text" placeholder="Subject" id="footer-subject" required>
<input type="submit" placeholder="Email">
</form>
</div>
<div class="footer__block mailing-list">
<span>Join our Mailing List!</span>
<form>
<input type="email" placeholder="Email" required>
<input type="submit">
</form>
</div>
<!-- <div class="grey-screen">
<div class="success">
<h1>Success!</h1>
</div>
</div> -->
<div class="progress-bar" ng-show="isEmailing">
</div>
</footer>
If you have several controller of same type it is not mean, that they all are same the instance. AngularJS creates controllers not via singleton pattern. You should synchronize them by yourself by means of events:
angular.module('app', [])
.controller('MyController', ['$scope', '$rootScope', function($scope, $rootScope) {
$rootScope.$on('Changed', function(event, data){
$scope.isEmailing = data;
})
$scope.successOnClick = function(){
$scope.$emit('Changed', !$scope.isEmailing);
}
}]);
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MyController">
<h3 ng-style="{'background-color' : isEmailing ? 'red' : 'white'}">First controller</h3>
<input type='button' ng-click='successOnClick()' value='Change color'/>
</div>
<div ng-controller="MyController">
<h3 ng-style="{'background-color' : isEmailing ? 'red' : 'white'}">Second controller</h3>
<input type='button' ng-click='successOnClick()' value='Change color'/>
</div>
</div>
If one controller located inside another you can try to use $scope.$parent.isEmailing(where .$parent can be typed several times, depending on nesting level), but it is very uncomfortable. If your controllers located at different routes, you should pass data from one controler to another via route parameters or custom AngularJS service or $rootScope.

How to search data with ng-click in angular js

I want to search data with ng-click function in angularJS, but when I try this code, it doesn't work.
First my button code:
<button id="veg" ng-click="myFilter = {type: 1}" title="veg">
My data display code:
<div class="side-body padding-top fade in tab-pane" id="<?php echo $tt3->id; ?>">
<div class="row">
<div ng-if='r.pro_category == <?php echo $tt3->id; ?>'
ng-repeat = "r in groups | filter : searchGroups | filter:myFilter">
<div>
<div class="thumbnail">
<div>
<img src="../#{{r.image }}" alt="" />
</div>
<div class="caption">
<div>#{{r.pro_name }}</div>
<div>#{{r.price}}</div>
</div>
</div>
</div>
</div>
My script code:
var GroupsApp = angular.module('GroupsApp',[]);
GroupsApp.controller('GroupsController', function ($scope, GroupsService) {
getGroups();
function getGroups() {
GroupsService.getGroups()
.success(function (grps) {
$scope.groups = grps;
return (val.type != 2);
console.log($scope.groups);
})
.error(function (error) {
$scope.status = 'Unable to load Product data: ' + error.message;
console.log($scope.status);
});
}
});
var url = window.location.pathname;
var productid = url.substring(url.lastIndexOf('/') + 1);
GroupsApp.factory('GroupsService', ['$http', function ($http) {
var GroupsService = {};
GroupsService.getGroups = function () {
return $http.get('../showproduct/'+productid);
};
return GroupsService;
}]);
When I run above code it doesn't show anything.
<button href="#" id="veg" ng-click="myFilter = {active: 1}" title="All Menu Items" class="bbb1 btn btn-info btn-lg " >

How to popup chat window using node.js

I am working on node.js and began to create a chat application I have built it successfully but the problem is that I want the chat window should be open when the client click on the name of the sender(who sent the message to the client).
I will show you the example what I have done till now.
Here you can see that the chat box is already open but I want it should open when a user is selected from "List of users" and the content of chat box should be replaced whenever a new user is selected and previous content should be removed.
Here is my index.html code :
<div class="col-md-4 user-list">
<h2>List of Users</h2>
<ul class="list-group">
<li class="list-group-item"
ng-repeat="user in userList"
ng-class="{ 'active' : user.id == selectedUser.uid}"
ng-click = seletedUser(user.id,user.userName);
ng-style="{
'cursor': user.id === socketId ? 'not-allowed' :'pointer'
}"
>
<span id='{{user.id}}' >{{ user.id === socketId ? 'You': user.userName }}</span>
<span id='{{user.id + "notify"}}' style="color:black; opacity:0.5; font:2px; padding:5px; visibility:hidden;"> {{'typing...'}}</span>
</li>
</ul>
</div>
</div>
<div class="container" id="messages">
<div class="row">
<div class="col-md-8">
<div class="panel panel-primary">
<div class="panel-heading">
<span class="glyphicon glyphicon-comment"></span> {{'Chat -' + selectedUser.uname}}
</div>
<div class="panel-body">
<ul class="chat col-md-7"
ng-repeat = "message in messages"
ng-style ="{'float':message.fromid == socketId ? 'left' : 'right'}">
<li>
<div class="clearfix">
<div class="direct-chat-text"
ng-style = "{'background-color': message.fromid == socketId ? '#d9edf7' : '#62f3bc'}"
>
{{message.msg}}
</div>
</div>
</li>
</ul>
<br></br>
</div>
<div class="panel-footer">
<div class="input-group">
<textarea elastic type="text" class="form-control custom-control" ng-model='message' ng-keyup="keyup()" ng-keydown="keydown()" ng-change="change()" placeholder="Type your message here..."></textarea>
<span class="input-group-addon btn btn-primary" ng-click="sendMsg()"><i class="glyphicon glyphicon-send"></i></span>
</div>
</div>
</div>
</div>
</div>
</div>
If you would require any other information related to code please comment.
As I am newbie to node.js so help me to solve my problem.
UPDATE
My script.js code which have sufficient details:
app.controller('app', ($scope,$timeout,socket) => {
$scope.socketId = null;
$scope.selectedUser ={ uid: null, uname: null};
$scope.messages = [];
$scope.msgData = null;
$scope.userList = [];
var TypeTimer;
var TypingInterval = 1000;
$scope.username = window.prompt('Enter Your Name');
if ($scope.username === '') {
window.location.reload();
}
$scope.seletedUser = (id,name) => {
if(id === $scope.socketId)
{
alert("Can't message to yourself.")
}
else
{
$scope.selectedUser =
{
uid: id,
uname: name
}
}
};
$scope.sendMsg = () => {
// const keyCode = $event.which || $event.keyCode;
if ($scope.message !== null && $scope.message !== '' && $scope.selectedUser.uid !== null) {
socket.emit('getMsg',{
toid : $scope.selectedUser.uid,
fromid: $scope.socketId,
msg : $scope.message,
name : $scope.username
});
$timeout.cancel(TypeTimer);
TypeTimer=$timeout( function(){
socket.emit('getTypingNotify',{
toid : $scope.selectedUser.uid,
fromid: $scope.socketId,
msg:"hidden"
});
});
$scope.message = null;
console.log($scope.selectedUser.uid);
}
else
{
alert("enter a message or select a User to send message");
}
};
socket.emit('username',$scope.username);
socket.on('userList', (userList,socketId) => {
if($scope.socketId === null){
$scope.socketId = socketId;
}
$scope.userList = userList;
});
socket.on('exit', (userList) => {
$scope.userList = userList;
});
socket.on('setMsg',(data) => {
document.getElementById(data.fromid+'notify').style.visibility= data.msg;
});
socket.on('sendMsg', (data) => {
//console.log('send');
$scope.messages.push(data);
});
my understanding is u want to show a pop up on click of a button or some text box u can use angular bootstarp model as shown here
"https://plnkr.co/edit/?p=preview"
and control the close and open in angularjs contoller and send the chat details too server side
After searching some tutorials and questions(on StackOverflow) I found a way and going to share with you all.
I created a directory name "open" and an attribute visible of this "open" directive to show and hide the dialog.
app.directive('open',function() {
return {
restrict: 'E',
template: `<div class="container">
<div class="row">
<div class="col-md-8">
<div class="panel panel-primary">
<div class="panel-heading">
<span class="glyphicon glyphicon-comment"></span>{{"Chat -" + selectedUser.uname}}
</div>
<div class="panel-body">
<div ppp-chat></div>
<br></br>
</div>
<div class="panel-footer">
<div class="input-group">
<textarea msd-elastic type="text" class="form-control custom-control" ng-model="message" ng-keyup="keyup()" ng-keydown="keydown()" ng-change="change()" placeholder="Type your message here..."></textarea>
<span class="input-group-addon btn btn-primary" ng-click="sendMsg()"><i class="glyphicon glyphicon-send"></i></span>
</div>
</div>
</div>
</div>
</div>
</div>`,
replace:true,
scope:false,
link: function postLink(scope,element,attrs) {
scope.$watch(attrs.visible,function(value){
if(value == true)
{
$(element).show();
}
else
$(element).hide();
});
$(element).on('show.bs.open',function() {
scope.$apply(function(){
scope.$parent[attrs.visible] = true;
});
});
$(element).on('hidden.bs.open',function() {
scope.$apply(function(){
scope.$parent[attrs.visible] = false;
});
});
}
};
});
And a method in controller to toggle the chat window(hide or show)
$scope.toggleChat = () => {
$scope.showChat = false;
$scope.showChat = !$scope.showChat;
};
this toggleChat is used to change the value of showChat scope variable that is used to turn on(off) the visibility of chat box by alterating the showChat value as true or false.
In html I have replaced my id="messages" element( with its child and subchild) with
<open visible="showChat">
</open>

How to check file type in kendo file upload using AngularJS?

I have kendo file upload with AngularJs which is working good for upload, Another requirement is Document Category is dropdown (Excel,Pdf,Word). Lets assume if user select excel from dropdown how can i restrict user to select only excel file by using onSelect method ?
So far tried code below...
main.html
<form name="addRiskForm" novalidate class="border-box-sizing">
<div class="modalForm">
<div class="row">
<div class="form-group col-md-12">
<label for="docCate" class="col-md-4">Document Category:</label>
<div class="col-md-8">
<select
kendo-drop-down-list
data-text-field="'text'"
data-value-field="'id'" name="attchCategory"
k-option-label="'Select'"
ng-model="attchCategory"
k-data-source="docCategoryOptions"
id="docCate">
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="issueNo" class="col-md-4">File name:</label>
<div class="col-md-6">
<input name="file"
type="file"
kendo-upload="fileAttachment"
k-upload="addMorePostParameters"
k-success="onSuccess"
k-error = "onError"
k-multiple="true"
k-options="fileAttachmentOptions"
k-select="onSelect"
/>
</div>
</div>
</div>
</div>
</form>
Ctrl.js
$scope.fileAttachmentOptions = assessmentDocConfig.fileAttachmentConfig;
$scope.docCategoryOptions = kendoCustomDataSource.getDropDownDataSource('RA_ATACH_TYP');
$scope.$on('addDocument', function (s,id){
$scope.riskAssessmentDTO.riskAssessmentKey = id;
$scope.viewDocumentWin.open().center();
});
$scope.addMorePostParameters = function (e) {
if (!$scope.attchCategory) {
e.preventDefault();
} else if (!$scope.attchDesc) {
e.preventDefault();
} else {
e.data = {
attchCategory:$scope.attchCategory,
attchDesc: $scope.attchDesc,
riskAssessmentKey: $stateParams.assessmentId,
};
}
};
$scope.onSuccess = function () {
$log.info('Upload Successfull...');
$scope.attchCategory = '';
$scope.attchDesc = '';
var filesToBeRemoved = $scope.fileAttachment.wrapper.find('.k-file');
$scope.fileAttachment._removeFileEntry(filesToBeRemoved);
console.log('Attachment Successfully Saved');
$scope.viewDocumentWin.close();
};
$scope.onSelect = function (e) {
$.each(e.file, function (index, value) {
var ok = value.extension == ".xlsx"
|| value.extension == ".pdf"
|| value.extension == ".doc"
|| value.extension == ".html";
if (value.extension === ok) {
e.preventDefault();
alert("Please upload jpg image files");
}
});
};
$scope.onError = function () {
$log.info('Upload Errored out...');
console.log('Error while uploading attachment');
};
config.js
fileAttachmentConfig: {
async: {
saveUrl: 'app/upload/uploadAttch',
removeUrl: 'remove',
removeVerb: 'DELETE',
autoUpload: false
},
template: '<span class=\'file-name-heading\'>Name:</span> <span>#=name#</span><button type=\'button\' class=\'k-upload-action\'></button>'
}
You could use the validation.allowedExtensions property, for example:
config.js
fileAttachmentConfig: {
async: {
saveUrl: 'app/upload/uploadAttch',
removeUrl: 'remove',
removeVerb: 'DELETE',
autoUpload: false
},
template: '<span class=\'file-name-heading\'>Name:</span> <span>#=name#</span><button type=\'button\' class=\'k-upload-action\'></button>',
validation: {
allowedExtensions: ["doc", "txt", "docx", "pdf", "jpg", "jpeg", "png", "xlsx", "xls"],
maxFileSize: 20000000, //20mb (in bytes)
}
}
In your specific example, you need to make this dynamic, so you should be able to adjust the values in the configuration object depending on what you've selected in the dropdown. So rather than referencing a static array, reference a variable that you can alter at runtime.
Further documentation:
https://docs.telerik.com/kendo-ui/api/javascript/ui/upload/configuration/validation#validation.allowedExtensions
https://demos.telerik.com/kendo-ui/upload/angular

Resources