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

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.

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.

Angular - Form won't submit

I seem to be overlooking something simple here but it has me stumped.
Why does nothing happen when i hit the submit button?
<section ng-controller="SavingsController as savingsCTRL">
<form name="createSavingForm" class="form-horizontal" novalidate>
<fieldset>
<!-- Title Box Start-->
<div class="form-group new-deal-form" show-errors>
<label for="title">Title</label>
<input name="title" type="text" ng-model="savingsCTRL.title" id="title" class="form-control" placeholder="Title" required>
<div class="sub-label">Enter the Title of the Deal.</div>
<div ng-messages="savingForm.savingsCTRL.title.$error" role="alert">
<p class="help-block error-text" ng-message="required">Saving title is required.</p>
</div>
</div>
<!-- Title Box End-->
<!--Submit Button Start-->
<div class="form-group buttons-cancel-submit">
<button class="btn btn-default " ng-click="savingsCTRL.cancel()">Cancel</button>
<input type="submit" class="btn btn-success " ng-click="savingsCTRL.create(); submitForm(createSavingForm.$valid)" >
</div>
</fieldset>
</form>
</div>
</div>
</section>
for simplicity i took most of the forms out but what else is wrong?
Savings Controller Function
// Create new Saving
$scope.create = function () {
$scope.error = null;
alert("create");
// Create new Saving object
var saving = new Savings({
title: this.title,
details: this.details,
retailer: this.retailer,
price: this.price,
link: this.link,
image: $scope.user.imageURL,
urlimage: this.urlimage,
tags: this.tags
//startdate: this.startdate,
//enddate: this.enddate
});
// Redirect after save
saving.$save(function (response) {
$location.path('savings/' + response._id);
// Clear form fields
$scope.title = '';
$scope.details = '';
$scope.retailer = '';
$scope.price = '';
$scope.link = '';
$scope.image = '';
$scope.urlimage = '';
$scope.tags = '';
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
Main issue is, you are mixing controller as syntax with $scope.
According to documentation, we should use this instead of $scope.
... binds methods and properties directly onto the controller using this: ng-controller = "SettingsController1 as settings"
Than, submitForm is not a predefined method, it should be defined in controller first
this.submitForm = function(isValid){
console.log('Submitting form: ' + isValid)
}
In addition to that, bind that to form with ng-submit= "savingsCTRL.submitForm(createSavingForm.$valid)"
See Plunker, with working code. (I took ng-click="savingsCTRL.create()", since we don't have all parts of your application)
Bind the form submit event to ng-submit.
Example: ng-submit="submitForm(createSavingForm.$valid)"

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

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.

Why won't this from scope variable at Angular JS controller is set to true?

I'm trying to code a controller so some inputs get disabled after changes in another one.
This is the controllre:
app.controller('SignUpController',function ($scope, $http) {
this.unavaliable = true
this.userUnavaliable = function() {
console.log(this.unavaliable)
return this.unavaliable
}
this.userExists = function(mail) {
if (mail) {
var who = $http.get("/existingUsers/"+mail)
who.success(function(data,status, headers, config) {
if (data.mail) {
this.unavaliable = true
console.log(data.mail + " ya existe en la DB")
}
else{
this.unavaliable = false
}
});
who.error(function(data, status, headers, config) {
alert("AJAX failed!");
})
}
}
})
As my markup below shows, one input should obtain a certain class, and another one should get disabled when unavaliable is set to true. But even I can get to the console.log(), the variable seems to never get true.
This is my markup:
<form class="form-inline" role="form">
<div class="form-group">
<input type="email" class="form-control input-lg" ng-model="signup.mail" placeholder="e-mail" ng-change="signup.userExists(signup.mail)" ng-class="{'has-error':signup.userUnavaliable()}">
</div>
<div class="form-group">
<input type="password" class="form-control input-lg" placeholder="ContraseƱa" ng-nodel="signup.password">
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="signup.role" value="admin"> Administrador
</label>
</div>
<button type="submit" class="btn btn-primary" ng-disabled="signup.unavaliable" >Registrar</button>
</form>
I tried with $scope instead of this but never got it to work that way
Try this:
app.controller('SignUpController',function ($scope, $http) {
var that = this;
that.unavaliable = true;
that.userUnavaliable = function() {
console.log(that.unavaliable)
return that.unavaliable
}
that.userExists = function(mail) {...
Your issue seems to be related to JS Context; in the example above it is preserved in that variable. That is how it is done in JOhn's Papa approach

angularJS inline editor for multiple 'fields'

The following code-snippet enables me to edit the elements on a page, however, clicking on the P tags all the others change into inline-editor mode as well. How can I rework this script, such that it only enables the editor for the P tag clicked?
JS code:
function Profile($scope) {
$scope.person = {
name : "Test Name",
company : "Test",
role : "Test Role"
};
}
function Editor($scope) {
$scope.editorEnabled = false;
$scope.enableEditor = function() {
$scope.editorEnabled = true;
$scope.name = $scope.person.name;
$scope.company = $scope.person.company;
$scope.role = $scope.person.role;
},
$scope.disableEditor = function() {
$scope.editorEnabled = false;
},
$scope.save = function() {
$scope.person.name = $scope.name; //var = input.value
$scope.person.company = $scope.company;
$scope.person.role = $scope.role;
$scope.disableEditor();
}
}
HTML:
<div ng-controller="Profile">
<div ng-controller="Editor">
<h1 class="center" ng:hide="editorEnabled" ng:click="enableEditor()">{{person.name}}</h1>
<span ng:show="editorEnabled">
<form class="form-inline">
<input type="text" size="30" name="name" ng:required ng-model="name">
<button class="btn btn-success" ng:click="save()">Ok</button>
<button class="btn btn-warning" ng:click="disableEditor()">Cancel</button>
</form>
</span>
<h5 class="center" ng:hide="editorEnabled" ng:click="enableEditor()">{{person.role}} # {{person.company}}</h5>
<span ng:show="editorEnabled">
<form class="form-inline">
<input type="text" size="30" name="role" ng:required ng-model="role"> # <input type="text" size="30" name="company" ng:required ng-model="company">
<button class="btn btn-success" ng:click="save()">Ok</button>
<button class="btn btn-warning" ng:click="disableEditor()">Cancel</button>
</form>
</span>
</div>
</div>
The way I would most likely approach it would be to introduce new field into $scope that identifies which field is editable. Then your ngShow directive would contain an expression, something along these lines:
<span ng:show="editable == 'company'">
Your ngClick directive would look something like this:
<h1 ng:click="editor = 'company'">
Your cancel button would set this to null and your enable/disable editor functions would be gone. Bear in mind all this is top of my head, hopefully it points you in the right direction. I'll improve this answer if I get a chance.

Categories