Add if data is new Or Update when data is different angularjs - javascript

I am trying to Update the data instead of adding (create) a new data when the image is changed (image is in base64)
I had also followed: http://jsfiddle.net/4Zeuk/12/ like what i tried to do below but i had tried my best at it but it update is not working. There are no errors.
Just for your information i am using ngCropper. https://github.com/koorgoo/ngCropper
EDIT: updated controller code
Angular code
app.controller("ProductAddCtrl", function($scope, $timeout, $resource, Product, Products, $location, Cropper) {
$scope.product = {item_name: '', price: '', category: ''}
var file, data;
$scope.saveImage = function(dataUrl) {
if (!file || !data) return;
if ($scope.product.currentImage){
Cropper.crop(file, data).then(Cropper.encode).then(function(dataUrl) {
($scope.preview || ($scope.preview = {})).dataUrl = dataUrl;
Product.update({id: $scope.product.id }, {product: { item_name: $scope.product.item_name, category: $scope.product.category, price: $scope.product.price, item_image: dataUrl, filename: file.name}},function(){
// $location.path('/');
console.log($scope.product)
}, function(error) {
console.log(error)
});
});
} else {
Cropper.crop(file, data).then(Cropper.encode).then(function(dataUrl) {
($scope.preview || ($scope.preview = {})).dataUrl = dataUrl;
Products.create({ product: { item_name: $scope.product.item_name, price: $scope.product.price, item_image: dataUrl, filename: file.name }}, function(){
// $location.path('/');
}, function(error){
console.log(error)
});
})
}
}
$scope.onChange = function() {
if ($scope.product.currentImage) {
$scope.product.item_image = $scope.product.currentImage.item_image;
$scope.product.filename = $scope.product.currentImage.filename;
} else {
$scope.product = {};
}
}
});
Angular Template file
<div class="content-push">
<input type="file" onchange="angular.element(this).scope().onFile(this.files[0])" ng-class="{'has-error' : productForm.item_image.$invalid}" ng-model="product.currentImage" ng-change="onChange" required>
<br />
<div ng-if="dataUrl" class="img-container">
<img ng-if="dataUrl" ng-src="{{dataUrl}}" width="300" height="300"
ng-cropper
ng-cropper-proxy="cropperProxy"
ng-cropper-show="showEvent"
ng-cropper-hide="hideEvent"
ng-cropper-options="options">
</div>
<br />
<button ng-click="preview()" class="btn btn-success">Show preview</button>
<button ng-click="zoomin()" class="btn btn-default">Zoom In</button>
<button ng-click="zoomout()" class="btn btn-default">Zoom Out</button>
<!-- <button ng-click="saveImage()" class="btn btn-default">Save</button> -->
<input type="submit" value="{{ product.currentImage.item_image ? 'Update' : 'Save' }}", class="btn btn-default" ng-click="saveImage()">
<div class="preview-container">
<img ng-if="preview.dataUrl" ng-src="{{preview.dataUrl}}" width="100" height: "100">
</div>
<select name="sellCategory" class="form-control" id="sellCategory" ng-model="product.category" required>
<option ng-repeat="option in categories.availableCategories" value="{{option.category}}">{{option.name}}</option>
</select>
<input type="text" ng-model="product.item_name" class="form-control" placeholder="Item Name" required>
<input type="text" ng-model="product.price" class="form-control" placeholder="Item Price" required>
</div>

I grasped the concept wrong.
Let's say i have multiple file upload feature in, instead of configuring angularjs to upload file one by one (via PUT request), i would select each file in base64 format (for preview) and then input the fields (like price, category and name of item) on the client side in angularjs instead of POSTing the PUTting each and every data.
So after everything on client side is set with image preview (i intend to have four) and data, then i would save (POST) it to the backend instead.
Thanks to everyone who looked at my question.

Related

Getting a 405 (Method Not Allowed) in AngularJS

So, I am creating a web app, where one page I have a user list and on the second page, I have the users details page. On the second page, I have a confirm button where I want to remove that user when the "Confirm" button is clicked with a 200 Status code. However, I am getting a DELETE : 405 (Method Not Allowed). So, here is my code down below. Please tell me or help me fix this problem. Thank you in advance.
Here is my code.
<div ng-controller="MyCtrl">
<div ng-repeat="person in userInfo.lawyers | filter : {id: lawyerId}">
<a class="back" href="#/lawyer">Back</a>
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="inactive = !inactive">Save</button>
<button class="btn btn-primary" ng-click="doDelete(id)">Confirm</button>
<div class="people-view">
<h2 class="name">{{person.firstName}}</h2>
<h2 class="name">{{person.lastName}}</h2>
<span class="title">{{person.email}}</span>
<span class="date">{{person.website}} </span>
</div>
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="person.firstName">
<br>
<b>Last Name:</b>
<input type="text" ng-model="person.lastName">
<br>
<b>Email:</b>
<input type="email" ng-model="person.email">
</fieldset>
</form>
</div>
</div>
</div>
Services
app.factory('people', function ($http) {
var service = {};
service.getUserInfo = function () {
return $http.get('https://api-dev.mysite.io/admin/v1/unconfirmed_lawyers');
};
service.confirmUser = function (lawyerId) {
return $http.put('https://api-dev.mysite.io/admin/v1/lawyers/{lawyerId}/confirm');
};
return service;
});
LawyerController
app.controller('LawyerController', ['$scope', 'people', '$routeParams',
function ($scope, people, $routeParams) {
$scope.lawyerId = $routeParams.id;
people.getUserInfo().then(function (response) {
$scope.userInfo = response.data;
});
}]);
HomeController
var isConfirmed = false;
app.controller('HomeController', function($scope, people, $http) {
if (!isConfirmed) {
people.getUserInfo().then(function (response) {
$scope.userInfo = response.data;
}, function (error) {
console.log(error)
});
}
});
App.js
$scope.doDelete = function(lawyer) {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
$scope.userInfo.lawyers.splice(index, 1);
location.href = '#/lawyer';
};
If you changed your HTML, so you passed the person instead.
<button class="btn btn-primary" ng-click="doDelete(person)">Confirm</button>
You can use this to find the index within the lawyers, then remove it.
$scope.doDelete = function(lawyer) {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
$scope.userInfo.lawyers.splice(index, 1)
};
The issue is your are using $http.delete which performs an HTTP Delete request. This doesn't sound like something you intended.

Clean way of posting form data with Angular?

I was wondering, what's the clean way of posting form data with angular?
I have this form setup
<div id="contact-form" class="row">
<div class="col-sm-4 col-sm-offset-4 text-center">
<form>
<div class="form-group">
<input type="text" class="form-control input-lg text-center" placeholder="Firstname" name="firstname" ng-model="firstname">
</div>
<div class="form-group">
<input type="text" class="form-control input-lg text-center" placeholder="Lastname" name="lastname" ng-model="lastname">
</div>
<div class="form-group">
<input type="email" class="form-control input-lg text-center" placeholder="Email" name="email"ng-model="email">
</div>
<!-- Submit Contact -->
<button type="submit" class="btn btn-primary btn-lg" ng-click="createContact()">Add</button>
</form>
</div>
</div>
and I'm posting this to a node.js backend "api".
How do I do this correctly? Do I write every api request in 1 core file? Do I make separate files for each page?
And then how I do I write a clean request?
$scope.createContact = function() {
$http.post('/contacts', ...)
.success(function(data) {
})
.error(function(data) {
});
};
I want to process 'lastname', 'firstname' and 'email' to add a new contact, but online I can't find a good, clean way to write this.
Here's my model in case it helps:
var mongoose = require('mongoose');
var ContactSchema = new mongoose.Schema({
firstname: { type: String, require: true },
lastname: { type: String, require: true },
email: { type: String, require: true }
});
module.exports = mongoose.model('Contact', ContactSchema);
Here's the code I used in the end.
$scope.createContact = function(contact) {
$scope.contact = { firstname: $scope.firstname, lastname: $scope.lastname, email: $scope.email };
$http.post('/contacts', $scope.contact)
.success(function(data) {
$scope.contact = {firstname:'',lastname: '', email:''}; // clear the form so our user is ready to enter another
$scope.contacts = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
How you structure your project is up to you. You could do it all in one file (but that's not very scalable), You could do one in each file (I wouldn't recommend it), or you could group them into semantic files like user_routes.js, social_media_routes.js, etc.
You are on the right track using $http.post() You'll want to create a JSON using your bound variables. You haven't included your entire controller so it's hard to tell you what to do. But a better way of doing this would probably just to create a JSON with empty values like this:
$scope.contact = {
firstname: '',
lastname: '',
email: '',
}
and then use something like ng-model="contact.firstname" for your data-binding. This will let you simply send $scope.contact to the back-end route.
The back-end route in Express would look something like:
var express = require('express');
var app = express();
app.post('/contacts', function (req, res) {
res.status(200).send(req)
}
This will send back what it receives - That should be enough to get you started - Handling POST requests in Express will depend on what version of Express you are using.
In the form tag add the attribute ng-submit to trigger directly in angular the post function.
<div id="contact-form" class="row">
<div class="col-sm-4 col-sm-offset-4 text-center">
<form ng-submit="createContact(user)">
<div class="form-group">
<input type="text" class="form-control input-lg text-center" placeholder="Firstname" name="firstname" ng-model="user.firstname">
</div>
<div class="form-group">
<input type="text" class="form-control input-lg text-center" placeholder="Lastname" name="lastname" ng-model="user.lastname">
</div>
<div class="form-group">
<input type="email" class="form-control input-lg text-center" placeholder="Email" name="email"ng-model="user.email">
</div>
<!-- Submit Contact -->
<button type="submit" class="btn btn-primary btn-lg">Add</button>
</form>
</div>
Add an empty user object in the controller:
$scope.user = {firstname:'',lastname: '', email:''};
Let the $http service handle the call:
$scope.createContact = function(user) {
$http.post('/contacts', user)
.then(function(data) {
//in data.data is the result of the call
},function(error) {
//here is the error if your call dont succeed
});};

How to add a control to a input file using angularjs?

I want to require an input of type file using angularjs without using the attribute required in the HTML code.
My interface is : enter image description here
I want to get an alert after hitting the button submit.
This is what I have done : enter image description here
function DatabaseCtrl($scope, $http, predefineds, locationSearch, queries, database, $window) {
var credentials = {
fileName: ""
};
$scope.credentials = credentials;
$scope.uploadToFolder = function() {
if( $scope.credentials.fileName.length<1 ) {
$window.alert("Please select a file!");
return false;
}
database.uploadToFolder($scope.credentials.fileName, true);
};
The HTML code :
<form role="form" name="frmUploadFolder" ng-submit="uploadToFolder()">
<div class="box">
<h2>
<span ng-show="isUserFile">File directory browser :</span>
<button type="button" ng-show="isUserFile" class="btn btn-default">See file(s)</button>
<button type="button" ng-show="!isUserFile" class="btn btn-default">Upload file(s)</button>
</h2>
<div class="content">
<p>
<label ng-show="isUserFile" >Please specify a file, or a set of files:</label><br>
<input type="file" ng-show="isUserFile" name="datafile" id="fileName" ng-model="credentials.fileName" size="20" required multiple>
<button type="submit" ng-show="isUserFile" class="btn btn-default" >Upload</button><br>
</p>
<div ui-if="!tree.length" class="message">
<p ui-if="!tree.loading">
<span ng-show="!isUserFile">Empty directory</span>
</p>
</div>
</div>
</div>
</form>
The service js :
angular.module('referl.services').factory('database', function($http, channel, $rootScope) {
var database = {
uploadToFolder: function(fileName, navigateOnSuccess) {
var parameters = {
fileName: fileName
};
$http.get("api/database/uploadToFolder", {params: parameters})
.success(function(response) {
if(response.error) {
alert(response.error);
} else {
if (navigateOnSuccess) {
alert("Navigation On Success !");
}
}
});
}
};
Any help please?
For some reason angular does not fully support binding a model element to a file input. The directive approach is generally the accepted work around, but within your controller you can also use document.getElementById("filename") to get a reference to the filename input and grab its value.

Angular Input Upload - Get file name and upload

I'm trying to create an image upload feature for a user profile update part of an Ionic/Angular application. The upload feature is part of the form and I am unable to retrieve the image and the filename. How would I get both items? Below is my code:
Form (View):
<div class="item-input">
<!--list item-->
<div data-ng-repeat="user in users">
Username: <input type="text" placeholder="Enter the event name" name="username" ng-model="user.username" required>
Password: <input type="password" placeholder="Enter the password" name="password" ng-model="user.password" required>
Email: <input type="text" placeholder="Enter the email" name="email" ng-model="user.email" required>
Hometown: <input type="text" placeholder="Enter your hometown" name="hometown" ng-model="user.hometown" required>
Firstname: <input type="text" name="firstname" ng-model="user.firstname" required>
Lastname: <input type="text" name="lastname" ng-model="user.lastname" required>
Birthday: <date-picker ng-model="user.birthday"></date-picker>
Image: <input type="file" name="file" ng-model="filename">
<button ng-click="upload(file)">Upload</button>
<button class="button button-block button-positive" ng-click="editprofile(user)">
Edit Account
</button>
<button class="button button-block button-positive" ng-click="deleteprofile()">
Delete Account
</button>
</div>
Controller
.controller('ProfileUpdateCtrl', function($http, $state, $http, $cordovaOauth, $stateParams, $rootScope, $scope, UserFac) {
//removed the working features to focus on the uploading part.
$scope.upload = function(file) {
var filename = $scope.file.name;
//need to know how to get the data of the image and save as formdata
}
});
I've created a sample uploading of image using angularjs. It retrieves the image and it's filename. I hope it may helps you.
HTML:
<div ng-app="test">
<div ng-controller="UploadCtrl">
Image:
<input type="file" name="file" onchange="angular.element(this).scope().photoChanged(this.files)" />
<img ng-src="{{ thumbnail.dataUrl }}" /> <!--Display the image -->
</div>
Controller:
angular.module('test', []);
angular.module('test') .controller('UploadCtrl', function($scope, $timeout) {
// Read the image using the file reader
$scope.fileReaderSupported = window.FileReader != null;
$scope.photoChanged = function(files) {
if (files != null) {
var file = files[0];
if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
$timeout(function() {
var fileReader = new FileReader();
fileReader.readAsDataURL(file); // convert the image to data url.
fileReader.onload = function(e) {
$timeout(function() {
$scope.thumbnail.dataUrl = e.target.result; // Retrieve the image.
});
}
});
}
}
};
});
JS Fiddle: https://jsfiddle.net/um8p6pd7/2/
Good luck!
You need to use $cordovaFileTransfer for uploading the file to the server.
Install the $cordovaFileTransfer plugin and then you will be able to upload file to the server and at the server side you need to make the path to get the file and save it on to the folder.

Getting data from the server and using ng-options in select control is failing to show options

this my HTML
<div ng-app="timeTable" ng-controller="addCoursesCtrl">
<button class="btn btn-primary" ng-click="addNewCourse()">Add New Course</button><br/><br/>
<fieldset ng-repeat="choice in choices">
<div class="row">
<div class="col-md-6">
<select class="form-control" ng-model="choice.type" ng-options="s for s in coursetoAdd">
<option value="{{s.shortCut}}">{{s.name}}</option>
</select>
</div>
<div class="col-md-6">
<input type="text" placeholder="Enter Course Name" name="" class="form-control" ng-model="choice.course"/>
</div>
</div>
<br/>
</fieldset>
<button class="btn btn-primary" ng-click="convertAndSend()">Submit</button>
</div>
this the js
var timeTable = angular.module("timeTable",[]);
timeTable.controller("addCoursesCtrl", function ($scope,$http) {
$scope.choices = [{ course: '', type: '' }];
$scope.coursetoAdd ;
$http.get("/Semster/getSuggtedCourses").then(function (response) {
$scope.coursetoAdd = response.data;
});
$scope.addNewCourse = function () {
var newITemNo = $scope.choices.length + 1;
$scope.choices.push({ course: '', type: '' });
};
$scope.convertAndSend = function () {
var asJson = angular.toJson($scope.choices);
console.log(asJson);
$http.post('/Semster/Add', asJson);
};
});
this code bind an object {"course":...,"type":....} every time you click on add course ,and add input field dynamically , my problem is with select control,I'm getting the data from server and use it with ng-optin ,but all it shows it's just [object Object] in select option not the real value.
Assuming that the data returned from getSuggestedCourses is an array of objects, the ng-options selector:
s for s in courseToAdd
will bind s to each object in the array. You need to bind to the fields in the object like this
s.value as s.name for s in courseToAdd

Categories