I am using a simple file upload as below:
<button type="file" ngf-select ng-model="fileData"
ng-change="fileChanged(fileData)" name="file" required >
Select File
</button>
And I have another button which when clicked I want to clear out the file that was selected.
<button type="button" class="btn btn-primary" ng-click="clearFile()">
Clear
</button>
I have the Controller code for button click as:
$scope.fileChanged = function(fileData) {
if (fileData != undefined) {
$scope.selectedFileName = fileData.name;
}
}
$scope.clearFile = function () {
//None of these works
//angular.element("input[type='file']").val(null);
// $scope.fileData = [];
}
I have tried couple of options as I searched through previous posts but none of it works. What am I missing here.
Here is my jsfiddle: http://jsfiddle.net/abco2Lp0/
Try this:
$scope.clearFile = function () {
$scope.fileData = [];
$scope.selectedFileName = null;
$scope.uploadedFile = [];
}
Hope this helps.
Related
I am uploading an .csv file using below code and it works perfectly. But I am facing one issue during the upload. When I the choose the .csv for the first time, submit button will get enabled, but when I choose the wrong file instead of .csv, button is not getting disabled. If I want to clear the selected file the clear button is not working. I am not to figure it out what is wrong.
Below is the code of controller where upload file functionality take place:
Html:
<div class="col-md-2" >
<input type="file" id="file1" name="file" ng-model="searchData" ng-files="getFiles($files)" multiple/>
</div>
<div class="col-md-2" style="padding:17px 0px 0px 55px">
<button type="button" ng-click="uploadFile()" ng-disabled="!flag">SUBMIT</button>
<button type="button" ng-click="clearFile()">CLEAR</button>
</div>
Angularjs:
var formData = new FormData();
$scope.getFiles = function ($files) {
var data = $files;
if (data.length > 0) {
formData.append('file1',data[0]);
var allData = formData.get('file1');
var filename = allData.name; // Here we will get file name with type
csvCheck = filename.substr(-4); // Here I am selecting the last four char, i.e (.csv)
if (csvCheck === ".csv") {
$scope.flag = true;
}
} else {
$scope.flag = false;
}
$timeout($scope.time(), 500);
};
Here is the plunker
Use this code to accept only CSV files :
In your HTML Use :
<input type="file" id="file1" name="file" onchange="angular.element(this).scope().getFiles(this)" multiple/>
Then in your controller use:
$scope.getFiles = function ($files) {
var validExts = new Array(".csv");
var fileExt = $files.value;
fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
if (validExts.indexOf(fileExt) < 0) {
alert("Invalid file selected");
$scope.flag=false;
}
else $scope.flag=true;
}
Use this code to clear the selected file :
document.getElementById("file1").value = "";
In my app i have a select html which has following options
"Addition","Deletion","Duplicate","Member Duplicate"
Above drop down page is common for both add and edit screen. As of now if we come from any addition click or edit click drop-down has all options. (Note: drop-down binds at the time of loading page itself. we will show/hide depending on click)
As per new requirement I need to remove all other options except "Addition" in addition click and remove "Addition" option in edit click.
select html:
<select name="ReasonID" required ng-model="member.ReasonID" class="form-control" ng-options="reason.ID as reason.Description for reason in reasons |orderBy: reason.Description"></select>
Js
$scope.manageMember = function (member) {
$scope.showGrid = false;
$scope.showForm = true;
reset();
$scope.memberTemp = member;
angular.extend($scope.member, member); };
Please let me know if you need more details from my end.
Update :
Here the full sample code and working demo with dummy data.
HTML
<div ng-app>
<h2>Todo</h2>
<div ng-controller="TodoCtrl">
<select name="ReasonID" required ng-model="member.ReasonID" class="form-control" ng-options="reason.ID as reason.Description for reason in reasons |orderBy: reason.Description"></select>
<br/>
<input type="button" ng-click="manageMember(undefined)" value="add"/>
<input type="button" ng-click="manageMember('bla bla bla')" value="edit"/>
</div>
</div>
JS
function TodoCtrl($scope) {
$scope.reasons = [{ID:1,Description :"Addition"}, {ID:2,Description :"Deletion"},{ID:3,Description :"Duplicate"},{ID:4,Description :"Member Duplicate"}];
var reasonsTemp =angular.copy($scope.reasons);
$scope.manageMember = function (member) {
console.log(reasonsTemp)
$scope.reasons=reasonsTemp;// assign global object to model
$scope.showGrid = false;
$scope.showForm = true;
$scope.memberTemp = member;
var EditArray=[];
for(var i = 0 ; $scope.reasons.length>i;i++)
{
if($scope.reasons[i].Description === ($scope.memberTemp == undefined ? "Addition" : "bla bla bla"))// condition for is this addition or not
{
EditArray = $scope.reasons[i];
break;
}
else // if is it not addition, then addition only offect that object. because we were already assigned original value globally
{
if($scope.reasons[i].Description!=="Addition")
{
EditArray.push($scope.reasons[i])
}
}
}
$scope.reasons=EditArray;
console.log($scope.reasons);
}
}
Working Demo On console window
Try this,
HTML
<select ng-model="selectedOption">
<option ng-show="reason.show" ng-repeat="reason.ID as reason.Description for reason in reasons |orderBy: reason.Description">{{reason.ID}}</option>
</select>
JS
$scope.manageMember = function (member) {
$scope.showGrid = false;
$scope.showForm = true;
reset();
$scope.memberTemp = member;
angular.extend($scope.member, member);
if(member){
for(var i = 0 ; $scope.reasons.length>i;i++)
{
$scope.reasons[i].show = true;
if($scope.reasons[i].ID == "Addition"){$scope.reasons[i].show = false;}
}
}else{
for(var i = 0 ; $scope.reasons.length>i;i++)
{
$scope.reasons[i].show = false;
if($scope.reasons[i].ID == "Addition"){$scope.reasons[i].show = true;}
}
}
}
Suppose you have two buttons as,
<input type="button" ng-click="toAdd=true">Add</input>
<input type="button" ng-click="toAdd=false">Edit</input>
And the select box code should be like,
<select ng-model="selectedOption">
<option ng-show="toAdd">Addition</option>
<option ng-show="!toAdd">Deletion</option>
<option ng-show="!toAdd">Duplicate</option>
<option ng-show="!toAdd">Member Duplicate</option>
</select>
Hope this helps.
Hi I am trying to change color as well as text of a button i.e. switch between two texts & colors. Suspend/unsuspend text and red/green color.
What I want to do is for the moment (because later, server will give info about whether user is suspended or not) randomly give them any one of these two texts&colors, and I click on button it should turn to other text & color.
I tried but I am wrong somewhere and I cant find it. Please help. And if there is any better way then please suggest to me, I am new to angular.
HTML:
<button type="button" class="btn btn-danger" ng-if="checkStatus(person.isSuspended)" ng-click="person.isSuspend=suspendUser(!person.isSuspend)">{{suspendText}}</button>
<button type="button" class="btn btn-primary" ng-if="checkStatus(!person.isSuspended)" ng-click="person.isSuspend=suspendUser(person.isSuspend)">{{suspendText}}</button>
Javascript:
$scope.checkStatus = function (bool) {
if (bool) {
$scope.suspendText = "UNSUSPEND"
return true;
} else {
$scope.suspendText = "SUSPEND"
return false;
}
}
$scope.suspendUser = function (bool) {
if (bool) {
if ($window.confirm("Are You Sure Want to Unsuspend ?")) {
$scope.suspendText = "SUSPEND"
return !bool;
}
else {
return bool;
}
} else {
if ($window.confirm("Are You Sure Want to Suspend ?")) {
$scope.suspendText = "UNSUSPEND"
return !bool;
} else {
return bool;
}
}
}
Check this Plunkr: http://plnkr.co/edit/DEbTtpwu749sVT6iSojd?p=preview
Asumming you are through a User List with name & status (boolean true: Active - false: inactive):
user = {name:'John', status: true}
Here you can check how change the status, text & button color. In a short angular Way.
<li ng-repeat="user in users">
({{ user.active ? 'Active' : 'Inactive'}})
{{ user.name }}
<div ng-class="user.active? 'btn btn-danger' : 'btn btn-primary' " ng-click="user.active=!user.active">
{{ user.active ? 'Suspend' : 'Unsuspend'}}
</div>
</li>
<body ng-controller="MainCtrl as vm">
<button class="btn"
ng-class="{ 'btn-primary': vm.isSuspended , 'btn-danger': !vm.isSuspended }"
ng-bind="vm.text"
ng-click="vm.toggleSuspend()">
</button>
</body>
angular.module('app', [])
.controller('MainCtrl', function() {
var vm = this;
vm.toggleSuspend = function() {
vm.isSuspended = !vm.isSuspended;
vm.text = vm.isSuspended ? 'unsuspend' : 'suspend';
};
vm.isSuspended = true;
vm.toggleSuspend();
});
You will just need one button instead of two. A better way of showing the colors would be using ng-class, where you can write expressions to toggle the class.
<button type="button" class="btn" ng-class="person.isSuspended? 'btn-danger':'btn-success'" ng-click="person.isSuspended = !person.isSuspended">{{suspendText}}</button>
Note the way ng-class is written. I am using ternary operator to check if person.isSuspeneded is true, if it is, apply the class btn-danger, else apply btn-success. Now you have got a way cleaner code.
Attached is the plnkr - http://plnkr.co/edit/Uk2rHFacMFLbXyxGzK1b?p=preview
Try to replace your ng-if with ng-show in button.
<div ng-controller="MyCtrl">
<button type="button" class="btn btn-danger"
ng-show="person.isSuspend"
ng-click="person.isSuspend=suspendUser(!person.isSuspend)">{{suspendText}}</button>
<button type="button" class="btn btn-primary"
ng-show="!person.isSuspend"
ng-click="person.isSuspend=suspendUser(person.isSuspend)">{{suspendText}}</button>
</div>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope, $window) {
// first you need to initialize your scope if you didn't
$scope.person = {
isSuspend: false
};
$scope.suspendText = "SUSPEND";
$scope.suspendUser = function (bool) {
if (bool) {
if ($window.confirm("Are You Sure Want to Unsuspend ?")) {
$scope.suspendText = "SUSPEND"
$scope.person.isSuspended = false;
}
else {
$scope.person.isSuspended = true;
}
} else {
if ($window.confirm("Are You Sure Want to Suspend ?")) {
$scope.suspendText = "UNSUSPEND"
$scope.person.isSuspended = true;
} else {
$scope.person.isSuspended = false;
}
}
}
}
angular change button text
I'm trying to reset background-colors (bgNeutral) of all my buttons, except the only one who are solicited (who have to switch in "bgSelected"):
<button ng-class="button1" ng-click="addActifOnMe($1)" class="bgSelected"></button>
<button ng-class="button2" ng-click="addActifOnMe($2)" class="bgNeutral"></button>
<button ng-class="button3" ng-click="addActifOnMe($3)" class="bgNeutral"></button>
This is my .js:
app.controller("angularController", function ($scope) {
$scope.button1 = "bgSelected";
$scope.addActifOnMe = function (1) {
$scope.button2 = "bgNeutral";
$scope.button3 = "bgNeutral";
$scope.button1 = "bgSelected";
};
$scope.addActifOnMe = function (2) {
$scope.button1 = "bgNeutral";
$scope.button3 = "bgNeutral";
$scope.button2 = "bgSelected";
};
$scope.addActifOnMe = function (3) {
$scope.button1 = "bgNeutral";
$scope.button2 = "bgNeutral";
$scope.button3 = "bgSelected";
};
});
CSS can be something like that:
.bgSelected{
background-color: red;
}
.bgNeutral{
background-color: blue;
}
But actually this, doesn't work... I'm trying to use ngClick with $event in my function. Someone have a better way for doing that ?
Thank you ! Best regards.
You can do this by using a variable selectedButton in your controller to track which button is selected.
<button class="neutral" ng-class="{selected: todoList.selectedButton === 1}" ng-click="todoList.select(1)">button 1</button>
<button class="neutral" ng-class="{selected: todoList.selectedButton === 2}" ng-click="todoList.select(2)">button 2</button>
<button class="neutral" ng-class="{selected: todoList.selectedButton === 3}" ng-click="todoList.select(3)">button 3</button>
controller:
angular.module('todoApp', [])
.controller('TodoListController', function() {
var todoList = this;
todoList.selectedButton = 1;
todoList.select = function(buttonNumber) {
todoList.selectedButton = buttonNumber;
}
});
Here's a plunker to demonstrate this working
I am facing a problem with my angular js bindings not being updated correctly.
I am trying to achieve a way to hide certain form elements and show others by clicking a "next" button.
I have setup some objects in my controller to hold values for input text fields and menu dropdowns, I also have setup a couple of button (next and previous and add) button to be able to add new objects and a next and previous buttons to be able to navigate between the different stored objects.
The problem that I am facing is that the input text field is being updated correctly when i press the next and previous button however the dropdown menus are not.
This is a link to a jsfiddle to help show the problem:
http://jsfiddle.net/bLs9yu3f/
Found two issues with the code in your Fiddle:
First, when assigning programOutcomes to the affects key of your objects (both when creating the initial one and pushing to add a new one) you where assigning programOutcomes directly, which assigns a pointer to the original array and doesn't create a copy. There are many ways to do this. I chose affects: JSON.parse(JSON.stringify(programOutcomes)). See the example below.
$scope.output.outcomes.push({
outcome: '',
affects: JSON.parse(JSON.stringify(programOutcomes))
});
Second, in the for loop of your addCourseOutcome function you refer to $scope.output.outcomes[0] instead of the latest $scope.output.outcomes you just pushed. The following code fixes this issue.
var lastest = $scope.output.outcomes.length - 1;
for (var i = 0; i < programOutcomes.length; i++) {
$scope.output.outcomes[lastest].affects[i].how = '';
}
This is a fork of your Fiddle with the corrections I mentioned above: http://jsfiddle.net/JohnnyEstilles/uz8zf2b0/.
angular.module('myapp', []).controller('ProgramsController', ['$scope',
function($scope) {
var programOutcomes = [{
outcome: 'po1'
}, {
outcome: 'po2'
}, {
outcome: 'po3'
}, {
outcome: 'po4'
}];
$scope.input = {
outcomeCounter: 0,
programOutcomes: programOutcomes,
actions: ['', 'I', 'E', 'R']
};
$scope.output = {
outcomes: [{
outcome: '',
affects: JSON.parse(JSON.stringify(programOutcomes))
}]
};
for (var i = 0; i < programOutcomes.length; i++) {
$scope.output.outcomes[0].affects[i].how = '';
}
$scope.nextOutcome = function() {
$scope.input.outcomeCounter++;
};
$scope.previousOutcome = function() {
$scope.input.outcomeCounter--;
};
$scope.deleteCourseOutcome = function() {
$scope.output.outcomes.splice($scope.input.outcomeCounter, 1);
$scope.input.outcomeCounter--;
};
$scope.addCourseOutcome = function() {
$scope.output.outcomes.push({
outcome: '',
affects: JSON.parse(JSON.stringify(programOutcomes))
});
/**
* create a 'how' property in the affects array
* to be used for storage of I, E, R
*/
var lastest = $scope.output.outcomes.length - 1;
console.log($scope.output.outcomes[lastest].affects);
for (var i = 0; i < programOutcomes.length; i++) {
$scope.output.outcomes[lastest].affects[i].how = '';
}
/**
* increment the outcomeCounter
*/
$scope.input.outcomeCounter++;
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myapp">
<div ng-controller="ProgramsController">
<div class="form-group">
<label for="outcome">Outcome</label>
<input id="outcome" placeholder="Outcome" class="form-control" ng-model="output.outcomes[input.outcomeCounter].outcome">
</div>
<div class="form-group">
<table class="table table-striped">
<tr ng-repeat="programOutcome in input.programOutcomes">
<td>{{programOutcome.outcome}}</td>
<td>
<select ng-model="output.outcomes[input.outcomeCounter].affects[$index].how" ng-options="value for value in input.actions">
</select>
</td>
</tr>
</table>
</div>
<div class="form-group">
<button class="btn" ng-click="addCourseOutcome()">Add outcome</button>
<button class="btn" ng-click="nextOutcome()"
ng-if="output.outcomes.length>1 && input.outcomeCounter !== (output.outcomes.length - 1)">
Next
</button>
<button class="btn" ng-click="previousOutcome()"
ng-if="output.outcomes.length>1 && input.outcomeCounter > 0">
Previous
</button>
<button class="btn btn-warning" ng-click="deleteCourseOutcome()">Delete outcome</button>
</div>
</div>
</body>