Save current date in database - angularjs

so i have an entity in which i want to put the current date while saving a form, without inputs for that date.
<tr>
<td> Emise aujourdh'hui le : </td>
<td > {{dateEmission | date:'dd-MM-yyyy'}}</td>
</tr>
and the js is :
//Get current date
$scope.dateEmission = new Date();
//save demande
$scope.savedemande = function() {
$http.post("/createDemande", $scope.demande).success(function(data) {
if (!data.errors) {
$scope.demande=data;
$scope.errors = null;
}
else {
}
})
.error(function(data) {
$scope.exception.message=data.message;
});
};

you want to pass dateEmission to the server with the POST request, is it? the key, dateEmission doesnt seem to be part of $scope.demande. How about:
$scope.savedemande = function() {
var today=new Date();
var date= today.toLocaleDateString() + today.toLocaleTimeString();
$scope.demande.dateEmission=date;
$http.post("/createDemande", $scope.demande).success(function(data) {
if (!data.errors) {
$scope.demande=data;
$scope.errors = null;
}
else {
}
})
.error(function(data) {
$scope.exception.message=data.message;
});
};

Related

Generated password using angular js not working

I want to make the password is auto generated and to pass it to the controller :
this is my view.jsp:
<tr>
<td class="leftDetails">Password</td>
<td class="rightDetails"><input type="text" name="password" ng-model="newUser.password" ng-disabled="isEditMode" id="p"/></td>
<td class="rightDetails"><input type='button' value ='generate' onclick='document.getElementById("p").value = Password.generate(16)' ng-show="add"></td>
<td class="leftDetails"></td>
<td class="rightDetails"></td>
</tr>
<script>
var Password = {
_pattern : /[a-zA-Z0-9_\-\+\.]/,
_getRandomByte : function()
{
if(window.crypto && window.crypto.getRandomValues)
{
var result = new Uint8Array(1);
window.crypto.getRandomValues(result);
return result[0];
}
else if(window.msCrypto && window.msCrypto.getRandomValues)
{
var result = new Uint8Array(1);
window.msCrypto.getRandomValues(result);
return result[0];
}
else
{
return Math.floor(Math.random() * 256);
}
},
generate : function(length)
{
return Array.apply(null, {'length': length})
.map(function()
{
var result;
while(true)
{
result = String.fromCharCode(this._getRandomByte());
if(this._pattern.test(result))
{
return result;
}
}
}, this)
.join('');
}
};
My problem is want to pass the generated password to my controller ,it was empty
How to correct that. thanks in advance?
The angular way to solve this issue is to update your input ng-model instead of selecting the element (Jquery way).
Instead of onClick use ng-click="newUser.password = Password.generate(16)"

Validate CSV file in angularJs

I have a csv file which contains two columns store_id and store_name.When the user uploads a csv file I need to validate the file i.e check if first column is Integer(store_id) and second column is String(store_name).Can you help how to read and retrieve the content and validate the file?
Thanks
Try this code
my csv file
store_id,store_name
01,"First point"
02,"Second point"
03,"Third point"
var demo = angular.module('demo', []);
demo.controller('loadData', function($scope,$rootScope,$http){
$scope.uploadData = function() {
var uploaded=$scope.fileContent;
$scope.processData(uploaded);
};
$scope.processData = function(allData) {
var filteredData = allData.split(/\r\n|\n/);
var headers = filteredData[0].split(',');
var final = [];
for ( var i = 0; i < filteredData.length; i++) {
if (!filteredData[i]=="") {
var data = filteredData[i+1].split(',');
if (isNaN(data[0])==false && isNaN(data[1])==true) {
final.push(data);
console.log("Valid CSV");
}
else{
console.log("Not Valid CSV");
}
}
}
$scope.data = final;
};
});
demo.directive('fileReader', function() {
return {
scope: {
fileReader:"="
},
link: function(scope, element) {
$(element).on('change', function(changeEvent) {
var files = changeEvent.target.files;
if (files.length) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
scope.$apply(function () {
scope.fileReader = contents;
});
};
r.readAsText(files[0]);
}
});
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
<div ng-app='demo'>
<div ng-controller='loadData'>
<input type="file" file-reader="fileContent" />
<button ng-click='uploadData($event)' >upload</button>
<div>{{fileContent}}</div>
<table>
<tr ng-repeat="x in data">
<td ng-repeat="y in x">{{ y }}</td>
</tr>
</table>
</div>
</div>
document.getElementById('csvUpload').onchange = function(){
var file = this.files[0];
var storeId = [],storeName = [],line,flag = 1;
var reader = new FileReader();
reader.onload = function(progressEvent){
var lines = this.result.split('\n');
for(var iterator = 0; iterator < lines.length-1; iterator++){
line = lines[iterator].split(',');
storeId.push(line[0]);
storeName.push(line[1]);
}
var result = !storeId.some(isNaN);
for(var iterator = 0; iterator < storeName.length; iterator++) {
console.log(typeof storeName[iterator]);
if(typeof storeName[iterator] !== "string"){
flag = 0;
break;
}
}
if(result === false || flag === 0) {
var alert = mdDialog.alert({
textContent: 'Please select a valid csv file',
ok: 'Close'
});
mdDialog.show( alert );
}
};
reader.readAsText(file);
}
you may try this component
https://www.import-javascript-angular-xlsx-csv-validator.com/
it validates that and more

$scope array not getting updated

Inside a controller I have this code:
$rootScope.$on('chat_contact', function(event, data) {
var message = data.message;
if(data.key === 'IM_MSG') {
console.log("chat_contact.........");
var contact = $scope.contacts[message.sndrId];
if(contact) {
contact.lastMsg = message.text;
contact.sndrName = message.sndrName;
} else {
$scope.contacts[7] = {
'lastMsg': message.text,
'sndrName': message.sndrName
}
}
}
});
Here is my html code:
<li class="item item-avatar item-icon-left1 item-icon-right" ng-repeat="(id, contact) in contacts" ui-sref="app.chat-single" on-hold="moreOptions('{{id}}')">
<img src="venkman.jpg">
<h2>{{contact.sndrName}}</h2>
<p><span class='margin-l-10'>{{contact.lastMsg}}</span></p>
Problem is
$scope.contacts[7] = {
'lastMsg': message.text,
'sndrName': message.sndrName
}
is adding a new enter to contacts but its not getting render in html
Can you try adding $apply() ?
I was facing the same problem and it resolved mine.
$scope.$apply(function(){
$scope.contacts[7] = {
'lastMsg': message.text,
'sndrName': message.sndrName
}
});
I'm not sure if it's correct but you can give it a try.
use $scope.$apply(); after the loop execution
$rootScope.$on('chat_contact', function(event, data) {
var message = data.message;
if(data.key === 'IM_MSG') {
console.log("chat_contact.........");
var contact = $scope.contacts[message.sndrId];
if(contact) {
contact.lastMsg = message.text;
contact.sndrName = message.sndrName;
} else {
$scope.contacts[7] = {
'lastMsg': message.text,
'sndrName': message.sndrName
}
$scope.$apply();
}
}
});

highlighting previous row after ng-click

I have a dropdownlist which contains brand ids. acccording to the id im fetching corresponding products and showing it in a table. There are two buttons in each row that move the products up and down basically by interchanging the ranks. now i am able to do all the functionality of interchanging and re binding.The row is selected when it is clicked. my only problem is i am not able to select the row after it has moved up or down.
<div ng-app="myapp" ng-controller="prodctrl">
<select id="BrandDropdown" class="InstanceList" ng-change="GetBrandProd()" ng-model="Products">
<option>Select Brand</option> //Sample Data
<option value=1>Brand 1<option>
<option value=2>Brand 2<option>
</select>
<table id="prodtab" ng-model="Products">
<tr ng-repeat="P in Products track by $index" ng-click="setselected($index)" class="{{selected}}">
<td>{{P.Id}}</td>
<td>{{P.Rank}}</td>
<td>{{P.Name}}</td>
<td>
<input type="button" value="Move Up" id="moveup" ng-click="getval(P,$index)" /></td>
<td>
<input type="button" value="Move Down" /></td>
</tr>
</table>
</div>
this is the angularjs code
<script>
var app = angular.module('myapp', []);
var prod = null;
var mveup = null;
var mvedwn = null;
var ind = null;
app.controller('prodctrl', function ($scope, $http) {
//getting products for each brand
$scope.GetBrandProd = function () {
cursel = "B";
var Id = $('#BrandDropdown').val();
fetchtype = Id;
brid = Id;
$http({
method: "GET",
url: "/Home/GetProdBrand",
params: {
id: Id
}
})
.success(function (response) {
var data = response;
$scope.Products = data;
prod = data;
});
};
//changing color of row when clicked
$scope.setselected = function (index) {
if ($scope.lastSelected) {
$scope.lastSelected.selected = '';
}
if (mveup == null) {
this.selected = 'trselected';
$scope.lastSelected = this;
}
else {
mveup = null;
//this.selected = '';
$(this).closest('tr').prev().prop('Class', 'trselected');
}
};
//function to move product up in ranking
$scope.getval = function (p, index) {
var Idcur = p.Id;
var Rankcur = p.Rank;
ind = index;
if ($scope.Products[index - 1] != null) {
var IdPrev=$scope.Products[index - 1].Id;
var Rankprev = $scope.Products[index - 1].Rank;
mveup = null;
$scope.lastSelected = this;
if (cursel == "B") {
fetchtype = brid;
}
else if (cursel == "C") {
}
mveup = true;
$http({
method: "GET",
url: "/Home/MoveProd",
params: {
Curid: Idcur,
CurRank: Rankcur,
ChngId: IdPrev,
ChngRnk: Rankprev,
Type: cursel,
Id: fetchtype
}
})
.success(function (response) {
// ranks are interchanged and the data is returned.
var data = response;
$scope.Products = data;
prod = data;
});
}
}
})
</script>
It seems, the way you are handling the row selection is not correct.
I have just changed the way of handling selection here.
<tr ng-repeat="P in Products track by $index" ng-click="setselected($index)" ng-class="{selected: selectedIndex == $index}">
//JS
$scope.setselected = function(index) {
$scope.selectedIndex = index;
};
Also, I have done a plunker with some sample values to imitate your requirement, you can ask more, if it is not fit to your requirement.
Plunker
You already have the id of the product that was clicked on (I think from looking at your code, it's Idcur), so you could loop over your results in the success block of the /Home/MoveProd GET request and set the record with the matching id to selected? Something like
var products = $scope.Products.filter(function(product) {
return product.id == Idcur;
})
if (products && products.length > 0) {
products[0].selected = 'trselected';
}
then, in your page, just update the ng-repeat slightly to pick the selected class from the product, instead of the scope, so:
<tr ng-repeat="P in Products track by $index" ng-click="setselected($index)" class="{{selected}}">
becomes
<tr ng-repeat="P in Products track by $index" ng-click="setselected($index)" class="{{P.selected}}">
or something like that :)

Angularjs Highlight is displaying last row (i.e; $index) after sorting the name

I am sorry for posting questions regularly about Angularjs, I am new to this and lot of confustion is there this is the reason I am posting the questions.
My doubt is I have a list of names whenever I created a new list the highlight is displaying the created name which is working but when I tried to set that names in alphabetical order the highlight issue is displaying the new $index value which is adding. I tried to pass the id in place of $index which is not and highlight is also not displaying. Here is the code which i tried
<table data-ng-repeat="SupplierModels in Supplierlist | filter:suppliersearch">
<tr>
<td class="roundedCorners6_account" ng-class='{roundedCorners6_account_active: $index==selectedRowslist}' style="width: 200px; cursor: pointer; text-align: center;">
<div ng-click="showSupplier(SupplierModels.supplier_ID, $index)">{{SupplierModels.supplier_Name | truncate}}</div>
</td>
</tr>
</table>
$scope function is
function initialLoading() {
ServiceFactory.Invoke(baseurl + 'Api/SupplierApi/SupplierList').success(function (success) {
$scope.Supplierlist = success;
}).error(function (error) {
alert(error);
})
}
$scope.SaveSupplier = function () {
$scope.IsValidatesupplierData($scope);
if ($rootScope.alerts.length == 0) {
ServiceFactory.InvokeWithParameters(baseurl + 'Api/SupplierApi/SaveSupplier', $scope.supplier).success(function (success) {
initialLoading();
var rows = $scope.selectedRowslist == undefined ? $scope.Supplierlist.length : $scope.selectedRowslist;
var supId = success;
$scope.showSupplier(supId, rows);
$scope.visible = true;
}).error(function (error) {
alert(error);
})
}
else {
$rootScope.isErrorPopUpShow = true;
}
}
$scope.showSupplier = function (id, rows) {
$scope.visible = true;
ServiceFactory.InvokeWithParameters(baseurl + 'Api/SupplierApi/SupplierDetail?supplierId=' + id).success(function (success) {
$scope.supplier = success;
$scope.selectedRowslist = rows;
}).error(function (error) {
alert(error);
})
}
I hope I gave a proper explanation. Thanks
I think it would be better to use a natural id in the data model.
id would work, but does supplier have an id field? If so you could use that.
<td class="roundedCorners6_account"
ng-class='{roundedCorners6_account_active: activeSupplierID== SupplierModels.supplier_ID}'
$scope.showSupplier = function (id, rows) {
$scope.visible = true;
ServiceFactory.InvokeWithParameters(baseurl + 'Api/SupplierApi/SupplierDetail?supplierId=' + id).success(function (success) {
$scope.supplier = success;
$scope.activeSupplierID = id; //supplier.id ? if it exists.
...
};

Resources