I'm using the below JS to feed options for my select:
//**** Instance des Bootstrap-SelectPicker ****
$('.selectpicker').selectpicker({
style: 'btn-info',
size: 4,
showSubtext: true,
noneSelectedText: 'Pas de sélection',
showSubtext: true,
showTick: true,
});
var menus = [
{ controleur: "CatDdeurs", element: "Cat_Ddeur" },
{ controleur: "Communautes", element: "Communaute" },
{ controleur: "Occupations", element: "Occupation" },
{ controleur: "Provinces", element: "Province" },
{ controleur: "Scolarites", element: "Scolarite" },
{ controleur: "Sexes", element: "Sexe" },
{ controleur: "Situations_Matrimoniales", element: "SituationMatrimoniale" },
{ controleur: "Source_De_Revenus", element: "SrceRevenu" },
{ controleur: "Statuts_Legaux", element: "StatutLegal" },
{ controleur: "Tranche_Revenu", element: "TrancheRevenu" },
{ controleur: "Villes", element: "Ville" },
{ controleur: "Sources_Informations", element: "SceInfo" },
{ controleur: "Langues", element: "langMaternelle" },
{ controleur: "Langues", element: "LangAutre" },
{ controleur: "Conseillers", element: "Conseiller" },
];
menus.forEach(x => {
MenusDeroulants('GetListe' + x.controleur, $('#cbx_' + x.element));
});
//**** Permet de remplir la liste des menus déroulants ****
function MenusDeroulants(url, dropdown) {
$.getJSON(url, function (data) {
dropdown.empty();
for (var i = 0; i < data.length; i++) {
var obj = data[i];
for (var key in obj) {
var prenom;
var nom;
var ID;
//**** Traitement des demandeurs ou conseillers ****
if (url == "GetListeConseillers" || url == "GetListeDemandeurs") {
//**** Retrait du code ****
if (key == 'Code_Conseiller' || key == 'Code_Demandeur') {
ID = obj[key];
};
//**** Retrait du Nom ****
if (key == 'Nom_Conseiller' || key == 'Nom_Demandeur') {
//if (key.match(/Nom_C*/) || key.match(/Nom_D*/)) {
nom = obj[key];
};
//**** Retrait du Prénom ****
if (key == 'Prenoms_Conseiller' || key == 'Prenoms_Demandeur') {
prenom = obj[key];
};
} else { //**** Traitement des autres menus ****
//**** Retrait de l'ID ****
if (key.match(/ID_*/)) {//**** Traitement des demandeurs ou conseillers ****
ID = obj[key];
};
//**** Retrait du Nom ****
if (key.match(/Nom_*/)) {
nom = obj[key];
};
};
}
//**** On construit les options du menu déroulant ****
if (url == "GetListeConseillers" || url == "GetListeDemandeurs") {
dropdown.append($("<option></option>").attr("value", ID).text(nom).attr("data-subtext", prenom));
} else {
dropdown.append($("<option></option>").attr("value", ID).text(nom));
};
if ((nom.toUpperCase() == "CHICOUTIMI" && url == 'GetListeVilles')
|| (nom.toUpperCase() == "QUÉBEC" && url == 'GetListeProvinces')
|| (nom.toUpperCase() == "NON DISPONIBLE" && url != 'GetListeVilles' && url != 'GetListeProvinces')) {
dropdown.prop("selectedIndex", i);
};
}
dropdown.selectpicker('refresh');
});
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>
<td style="padding-left:10px">
<div class="form-group">
<label for="cbx_Sexe" class="control-label">Sexe:</label>
<div>
<select class="selectpicker" id="cbx_Sexe"></select>
</div>
</div>
</td>
The first 12 elements will work fine but as soon as I add the 3 last, my selects will start behaving funny: The 3 lasts will sometimes work fine and some times show a white space on top of the box.
Sometimes, menus will not close when I open others... and so on.
I have tried combining the 12 first with each of the 3 lasts but there will always be something.
More strange is that if I use let say : "{ controleur: "Sexes", element: "Sexe" }," to fill all 3 that are giving me issue, all works perfectly.
Below is a screenshot of the display I'm getting:
Changing my function (MenusDeroulants) parameter dropdown to $dropdown finally solved the issue.
Related
I have a problem with reseting fields of my form.
I have a form. The user can adding another forms and another ...
If everything is OK, I would like to recording data in my DB and in my store AND reset all of inputs of my form. This is this last point I cannot do.
I have tried different solutions but It does not work.
This is my code :
<div v-for="(question, index) in questionsSignaletiques" :key="index" class="blockQuestion" >
<!--form to add questions : one form per question, each form have a different name in the ref -->
<a-form-model
layout="inline"
:ref="'p' + index"
>
<p>New question</p>
<a-alert v-if="question.error.here" type="error" :message="question.error.message" show-icon />
<a-form-model-item>
<a-input v-model="question.question.type" placeholder="Title">
</a-input>
</a-form-model-item>
<a-form-model-item>
<a-input v-model="question.question.item" placeholder="Item">
</a-input>
</a-form-model-item>
<br><br>
<a-form-model-item label="Question multiple" prop="delivery">
<a-switch v-model="question.question.multiple" />
</a-form-model-item>
<a-form-model-item label="Obligatoire" prop="delivery">
<a-switch v-model="question.question.obligatoire" />
</a-form-model-item>
<br><br>
<div class="blockChoices">
<div v-for="subrow in question.question.choices">
<a-form-model-item>
<a-input v-model="subrow.name" placeholder="Choix">
</a-input>
</a-form-model-item>
</div>
</div>
<a-button #click="addChoice(question)" type="secondary">Add a choice</a-button>
</a-form-model>
</div>
<div>
<a-button #click="addItem" type="secondary">Add a question</a-button>
</div>
<br>
<div>
<a-button #click="submit" type="primary">Send</a-button>
</div>
Javascript code :
data() {
return {
idStudy: this.$route.params.id,
aucuneQuestion:false,
questionsSignaletiques: [
{
"study":"/api/studies/" + this.$route.params.id,
"question":
{
type: "",
item: "",
multiple: false,
obligatoire: false,
inverse: false,
barometre: false,
originale: false,
signaletik: true,
choices: [{name:''}]
},
"error": {
message:"",
here:false
}
}
],
}
},
mounted() {
//retreive all the questions still recorded
axios
.get('http://127.0.0.1:8000/api/studies/' + this.idStudy + '/question_studies?question.signaletik=true')
.then((result)=>{
console.log(result.data["hydra:member"])
this.aucuneQuestion = result.data["hydra:member"].length === 0;
//on met les données dans le store
this.$store.commit("setListeQuestionsSignaletiques", result.data["hydra:member"])
})
.catch(err=>console.log(err))
},
methods: {
//Adding a question
addItem () {
this.questionsSignaletiques.push(
{
"study":"/api/studies/" + this.idStudy,
"question":
{
type: "",
item: "",
multiple: false,
obligatoire: false,
inverse: false,
barometre: false,
originale: false,
signaletik: true,
choices: [{name:''}]
},
"error": {
message:"",
here:false
}
}
)
},
//adding a choice
addChoice: function(choice) {
choice.question.choices.push({
name: ''
})
},
// Sending the forms
submit () {
//loop table to retrieve all questions and indexes if the user adding several questions
this.questionsSignaletiques.forEach((element,index) =>
{
const inputType = element.question.type
const inputItem = element.question.item
const inputChoice = element.question.choices
//loop on choices to see if empty one or not
for (const oneChoice of inputChoice)
{
if ((inputChoice.length == 1) ||(inputChoice.length == 2 && oneChoice.name == ""))
{
element.error.here=true
element.error.message = "You must have two choices at least"
return false; // stop here if error
}
else
{}
}// end loop of choices
// verify other fields
if (inputType == "" || inputItem =="")
{
element.error.here=true
element.error.message = "Title and item must not be empty"
}
else
{
// everything is ok we can record in db and store
//reset fields == does not work
this.$refs['p' + index][0].fields.resetField()
//this.$refs['p' + index][0].resetFields();
// adding questions in db one by one
/*
axios
.post('http://127.0.0.1:8000/api/question_studies', element)
.then((result)=>{
console.log(result)
//add in the state
this.$store.commit("addQuestionSignaletique", element)
})
.catch(error => {
console.log("ERRRR:: ",error);
});
*/
}
}) //end loop foreach
}
}
};
Thanks a lot for help
EDIT AFTER THE FIRST ANSWER
Ok I didn't know. So I changed my mind : I added a "show" in my "data" which is true at the beginning. If everything is ok, I save the question and set the show to false.
The problem now is that when I have a question that is OK and the other one that is not. When I correct the question that was not ok and save it, BOTH questions go into the STATE. So there is a duplicate in my state AND my DB... What can I do? This is the code :
I just added this in the HTML :
<div v-for="(question, index) in questionsSignaletiques" :key="index" >
<a-form-model
layout="inline"
v-if="question.show"
class="blockQuestion"
>
...
data() {
return {
idStudy: this.$route.params.id,
aucuneQuestion:false,
questionsSignaletiques: [
{
"study":"/api/studies/" + this.$route.params.id,
"question":
{
type: "",
item: "",
multiple: false,
obligatoire: false,
inverse: false,
barometre: false,
originale: false,
signaletik: true,
choices: [{name:''}]
},
"error": {
message:"",
here:false
},
"show":true,
}
],
}
},
mounted() {
//retrieve question still recorded
axios
.get('http://127.0.0.1:8000/api/studies/' + this.idStudy + '/question_studies?question.signaletik=true')
.then((result)=>{
console.log(result.data["hydra:member"])
this.aucuneQuestion = result.data["hydra:member"].length === 0;
this.$store.commit("setListeQuestionsSignaletiques", result.data["hydra:member"])
})
.catch(err=>console.log(err))
},
methods: {
//adding a question
addItem () {
this.questionsSignaletiques.push(
{
"study":"/api/studies/" + this.idStudy,
"question":
{
type: "",
item: "",
multiple: false,
obligatoire: false,
inverse: false,
barometre: false,
originale: false,
signaletik: true,
choices: [{name:''}]
},
"error": {
message:"",
here:false
},
"show":true
}
)
},
//adding a choice
addChoice: function(choice) {
choice.question.choices.push({
name: ''
})
},
// submit the form
submit () {
this.questionsSignaletiques.forEach((element,index) =>
{
const inputType = element.question.type
const inputItem = element.question.item
const inputChoice = element.question.choices
for (const oneChoice of inputChoice)
{
if ((inputChoice.length == 1) ||(inputChoice.length == 2 && oneChoice.name == ""))
{
element.error.here=true
element.error.message = "You must have two choices at least"
return false; //on s'arrête là si il y a une erreur
}
else
{
console.log("no problem")
}
}
if (inputType == "" || inputItem =="")
{
element.error.here=true
element.error.message = "You must fill type and item"
}
else
{
// hide the question form
element.show =false
//adding in db
axios
.post('http://127.0.0.1:8000/api/question_studies', element)
.then((result)=>{
//add in the state
this.$store.commit("addQuestionSignaletique", element)
})
.catch(error => {
console.log("ERRRR:: ",error);
});
}
}) //end loop foreach
}
}
};
Thanks for help !
form.reset() does not work when using v-model.
Reset the reactive data instead.
reset() {
this.question.question.type = ""
...
...
}
hi guys i am working on forget password in mobile app using nativescript, and i want to show alert message when the user insert wrong email or wrong apssword in the dialog , but i couldn't make it is there any body can help ?
let options: PromptOptions = {
title: "Entrez votre nouveau mot de passe",
okButtonText: "Suivant",
cancelButtonText: "Annuler",
cancelable: true,
inputType: inputType.password,
capitalizationType: capitalizationType.none
}; prompt(options).then((pass: PromptResult) => {
if (pass.text && pass.result == true) {
let options: PromptOptions = {
title: "Entrez votre nouveau mot de passe de nouveau",
okButtonText: "Suivant",
cancelButtonText: "Annuler",
cancelable: true,
inputType: inputType.password,
capitalizationType: capitalizationType.none
}; prompt(options).then((pass2: PromptResult) => {
if (pass2.text && pass2.result == true) {
if (pass.text == pass2.text) {
this.auth.resetMDP(this.email, this.code, pass2)
.then((res: any) => {
if (res.message == 'OK')
alert('votre mot de passe a été changé avec succès')
}).catch((err: any) => { alert(err); })
} else alert("re-entrez le mot de passe correctement s'il vous plait");
}
})
}
});
because i ve tried to make it work , but the dialog always close
In my apps I use modals to handle custom dialog styling and special action (as you require validation without closing the dialog). The easiest is:
This is how you call it:
page.showModal(
"you/path/to/modal/directory",
{
// your binding context
},
() => {
// on close callback
}
);
Assume that you have modal layout as XML and code behind (in my case Typescript):
<Page xmlns:RL="nativescript-ripple" xmlns="http://schemas.nativescript.org/tns.xsd" shownModally="onShownModally" >
<DockLayout stretchLastChild="false">
<Label dock="top" text="Hello Modal!!" horizontalAlignment="center" />
<TextView dock="top" text="{{ message }}" fontSize="15sp" horizontalAlignment="left" />
<Button dock="bottom" text="OK" tap="onOkTap" />
</DockLayout>
let closeCallback: () => void;
export function onShownModally(args: any) {
const page: Page = <Page>args.object;
const context = args.context;
// your close callback logic that you passed
closeCallback = args.closeCallback;
// bind you context object to modal
page.bindingContext = fromObject(context);
}
export function onOkTap(args: EventData) {
const page = args.object as Page;
if (closeCallback !== null && closeCallback !== undefined) {
closeCallback();
} else {
page.closeModal();
}
}
I have a calendar where users are going to register reminders and tasks, now I would like each user to see only their own tasks. Each task created is already associated with the user as I will be showing below, for this system I am using Codeigniter + FullCalendar (javascript), it follows my codes and images for better understanding:
Agenda:
View:
<head>
<script type="text/javascript">
$(function(){
$("#nomeEvento").autocomplete({
source: "clientes/get_cliente", // path to the method
appendTo: $("#new_event")
});
});
</script>
<script>
$(function(){
$('.form-control.date').datepicker({
format: 'yyyy-mm-dd',
language: 'pt-BR',
todayHighlight: true
});
});
</script>
<script>
$(document).ready(function() {
$.post('<?php echo base_url();?>calendar2/getEvents',
function(data){
alert(data);
$('#calendar').fullCalendar({
locale: 'pt-br',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
defaultDate: new Date(),
navLinks: true, // can click day/week names to navigate views
editable: true,
eventLimit: true, // allow "more" link when too many events
editable: true,
events: $.parseJSON(data),
eventDrop: function(event, delta, revertFunc){
var id = event.id;
var fi = event.start.format();
var ff = event.end.format();
$.post("<?php echo base_url();?>calendar2/updateEvents",
{
id:id,
inicio:fi,
fim:ff,
},
function(data){
if(data == 1){
alert('Evento atualizado');
}else{
alert('Evento Nao atualizado')
}
});
},
eventResize: function(event, delta, revertFunc) {
var id = event.id;
var fi = event.start.format();
var ff = event.end.format();
$.post("<?php echo base_url();?>calendar2/updateEvents",
{
id:id,
inicio:fi,
fim:ff,
},
function(data){
if(data == 1){
//alert('Evento atualizado');
}else{
// alert('Evento não atualizado')
}
});
},
// eventClick: function(event,jsEvent, view){
// $('#calendar').fullCalendar('removeEvents',event.id);
// }
eventRender: function(event, element,data){
var el = element.html();
element.html("<div style='width:90%;float:left;'>" + el + "</div><div class='closeee' style='color:red; text-align:right;'>X</div>");
element.find('.closeee').click(function(){
if(!confirm("Excluir registro ??")){
revertFunc();
}else{
var id = event.id
$.post("<?php echo base_url();?>calendar2/deleteEvents",
{
id:id,
},
function(data){
if(data == 1){
$('#calendar').fullCalendar('deleteEvents', event.id);
//alert('Tarefa Excluida');
}else{
//alert('Tarefa não Excluida')
}
});
}
});
},
eventClick: function(event, jsEvent, view){
$('#id').html(event.id);
$('#mtitulo').html(event.title);
$('#autor').html(event.autor);
$('#inicioEdit').val(event.start);
$('#importanciaEdit').val(event.impor);
$('#descricaoEventoEdit').val(event.text);
$('#modalEvento').modal();
},
});
});
});
$(function(){
$('.form-control.date').datepicker({
format: 'yyyy-mm-dd',
language: 'pt-BR',
todayHighlight: true
});
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Calendar2 extends CI_controller{
function __construct(){
parent:: __construct();
$this->load->model('calendar2Model', 'model', TRUE);
}
public function index(){
$this->template->set('title', 'Agenda');
$this->template->load('layout', 'calendar_v.php');
//$this->load->view('calendar_v.php');
}
public function getEvents(){
$data = $this->model->get_events();
echo json_encode($data);
}
public function updateEvents(){
$param['id'] = $this->input->post('id');
$param['inicio'] = $this->input->post('inicio');
$param['fim'] = $this->input->post('fim');
$r = $this->model->updateEvents($param);
echo json_encode($r);
}
public function updateEvents2(){
$this->load->library('form_validation');
/* Define as tags onde a mensagem de erro será exibida na página */
$this->form_validation->set_error_delimiters('<span>', '</span>');
/* Aqui estou definindo as regras de validação do formulário, assim como
na função inserir do controlador, porém estou mudando a forma de escrita */
$this->form_validation->set_rules('mtitulo', 'Nome', 'required|max_length[40]');
$this->form_validation->set_rules('autor', 'Autor', 'trim|required|max_length[100]');
$this->form_validation->set_rules('inicioEdit', 'Data', 'trim|required|max_length[20]');
$this->form_validation->set_rules('importanciaEdit', 'importancia', 'trim|required|max_length[20]');
$this->form_validation->set_rules('descricaoEventoEdit', 'Descricao', 'trim|required|max_length[60]');
/* Executa a validação e caso houver erro chama a função editar do controlador novamente */
if ($this->form_validation->run() === FALSE) {
$this->session->set_flashdata('mensagem', "<div class='alert alert-danger'> preencha todos os campos antes de salvar </div>");
redirect('clientes');
} else
/* Senão obtém os dados do formulário */
$data['idevento'] = $this->input->post('nomeEvento');
$data['nomeEvento'] = $this->input->post('mtitulo');
$data['inicio'] = $this->input->post('inicioEdit');
$data['fim'] = date('Y-m-d', strtotime($this->input->post('inicioEdit'). ' + 1 day'));
$data['user'] = $this->input->post('autor');
$data['importancia'] = $this->input->post('importanciaEdit');
$data['descricaoEvento'] = $this->input->post('descricaoEventoEdit');
/* Executa a função atualizar do modelo passando como parâmetro os dados obtidos do formulário */
if ($this->model->updateEvents2($data)) {
$this->session->set_flashdata('mensagem', "<div class='alert alert-success'> Cliente editado com sucesso</div>");
redirect('clientes');
} else {
$this->session->set_flashdata('mensagem', "<div class='alert alert-danger'> Erro ao editar cliente</div>");
}
}
public function deleteEvents(){
$id = $this->input->post('id');
$r = $this->model->deleteEvents($id);
echo json_encode($r);
}
public function new_event(){
$this->template->set('title', 'Nova tarefa');
$this->load->library('form_validation');
/* Define as tags onde a mensagem de erro será exibida na página */
$this->form_validation->set_error_delimiters('<span>', '</span>');
/* Define as regras para validação */
$this->form_validation->set_rules('nomeEvento', 'Nome', 'required|max_length[40]');
$this->form_validation->set_rules('inicio', 'Data de inicio', 'trim|required|max_length[60]');
$this->form_validation->set_rules('importancia', 'Prioridade', 'trim|required|max_length[60]');
$this->form_validation->set_rules('descricaoEvento', 'descricaoEvento', 'trim|required|max_length[150]');
/* Executa a validação e caso houver erro chama a função index do controlador */
if ($this->form_validation->run() === FALSE) {
$this->session->set_flashdata('mensagem', "<div class='alert alert-warning'> preencha todos os campos antes de salvar </div>");
redirect('clientes');
/* Senão, caso sucesso: */
} else {
/* Recebe os dados do formulário (visão) */
$data['nomeEvento'] = $this->input->post('nomeEvento');
$data['inicio'] = $this->input->post('inicio');
$data['fim'] = date('Y-m-d', strtotime($this->input->post('inicio'). ' + 1 day'));
$data['user'] = $this->input->post('user');
$data['importancia'] = $this->input->post('importancia');
$data['descricaoEvento'] = $this->input->post('descricaoEvento');
/* Chama a função inserir do modelo */
if ($this->model->inserir($data)) {
$this->session->set_flashdata('mensagem', "<div class='alert alert-success'> Lembrete salvo com sucesso</div>");
redirect('clientes');
} else {
$this->session->set_flashdata('mensagem', "<div class='alert alert-danger'> Erro ao salvar Lembrete </div>");
redirect('clientes');
}
}
}
}
Model:
<?php
class calendar2Model extends CI_Model {
function __construct() {
parent::__construct();
}
public function get_events(){
$this->db->select('idevento id, inicio start, fim end,descricaoEvento text, user autor,importancia impor ,cnome title');
$this->db->from('eventos');
$this->db->join('clientes','clientes.ccod = eventos.nomeEvento');
return $this->db->get()->result();
}
function inserir($data) {
return $this->db->insert('eventos', $data);
}
function updateEvents($param) {
$campos = array(
'inicio' => $param['inicio'],
'fim' => $param['fim']
);
$this->db->where('idevento', $param['id']);
$this->db->update('eventos', $campos);
if($this->db->affected_rows() == 1){
return 1;
} else{
return 0;
}
}
function deleteEvents($id){
$this->db->where('idevento', $id);
$this->db->delete('eventos');
if($this->db->affected_rows() == 1){
return 1;
} else{
return 0;
}
}
}
With Blueimp / Jquery File Upload, I can going to preview :
done: function (e, data) {
var file = data.files[0];
console.log(data.files[0]);
console.log(data.result.files); // always undefined ...
$(this).closest('tr').find('input[type=text]').val(file.name.substr(0, file.name.lastIndexOf('.')));
$(this).remove();
},
Return :
Blob { name: "IMG_20160512_225352.jpg", preview: canvas, size: 221398, type: "image/jpeg" }
But, If I added "add" options, I don't have preview :
add: function (e, data) {
var goUpload = true;
var file = data.files[0];
if (!(/\.(gif|jpg|jpeg|png)$/i).test(file.name)) {
$(this).closest('tr').find('td:first').prepend('<div class="alert alert-danger text-justify"><ul class="list-unstyled"><li><span class="glyphicon glyphicon-exclamation-sign"></span> Seuls les types de fichiers suivants sont autorisés : .gif ; .jpg ; .jpeg ; .png</li></ul></div>');
goUpload = false;
}
if (file.size > 2000000) {
$(this).closest('tr').find('td:first').prepend('<div class="alert alert-danger text-justify"><ul class="list-unstyled"><li><span class="glyphicon glyphicon-exclamation-sign"></span> La taille maximale autorisée par fichier est de 2 Mo</li></ul></div>');
goUpload = false;
}
if (goUpload === true) {
data.submit();
}
},
done: function (e, data) {
var file = data.files[0];
console.log(data.files[0]);
console.log(data.result.files); // always undefined ...
$(this).closest('tr').find('input[type=text]').val(file.name.substr(0, file.name.lastIndexOf('.')));
$(this).remove();
},
Return :
File { name: "IMG_20160512_225352.jpg", lastModified: 1463086668000, lastModifiedDate: Date 2016-05-12T20:57:48.000Z, size: 1034928, type: "image/jpeg" }
Can you help me ? I want to going to preview for print him.
Full JS code :
$('.file_upload:last').fileupload({
dataType: 'json',
url: '/app_dev.php/_uploader/gallery/upload',
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator && navigator.userAgent),
imageMaxWidth: 1200,
imageMaxHeight: 1200,
previewMaxWidth : 350,
previewMaxHeight : 350,
imageCrop: false,
autoUpload: true,
/*
add: function (e, data) {
var goUpload = true;
var file = data.files[0];
if (!(/\.(gif|jpg|jpeg|png)$/i).test(file.name)) {
$(this).closest('tr').find('td:first').prepend('<div class="alert alert-danger text-justify"><ul class="list-unstyled"><li><span class="glyphicon glyphicon-exclamation-sign"></span> Seuls les types de fichiers suivants sont autorisés : .gif ; .jpg ; .jpeg ; .png</li></ul></div>');
goUpload = false;
}
if (file.size > 2000000) {
$(this).closest('tr').find('td:first').prepend('<div class="alert alert-danger text-justify"><ul class="list-unstyled"><li><span class="glyphicon glyphicon-exclamation-sign"></span> La taille maximale autorisée par fichier est de 2 Mo</li></ul></div>');
goUpload = false;
}
if (goUpload === true) {
data.submit();
}
},
*/
done: function (e, data) {
var file = data.files[0];
console.log(data);
console.log(data.files[0]);
console.log(data.result.files);
$(this).closest('tr').find('input[type=text]').val(file.name.substr(0, file.name.lastIndexOf('.')));
$(this).remove();
},
progressall: function (e, data) {
var input_this = this;
var progress = parseInt(data.loaded / data.total * 100, 10);
$(input_this).closest('tr').find('.upload-progress .progress-bar-current').text(progress + '%');
$(input_this).closest('tr').find('.upload-progress .progress-bar-current').css(
'width',
progress + '%'
);
},
fail: function(e, data) {
var input_this = this;
$(input_this).closest('tr').html('<td colspan="3" class="text-center background-orange"><i class="fa fa-exclamation-circle"></i> Erreur lors du transfert du fichier, veuillez vérifier qu\'il soit conforme (notamment types de fichiers autorisés, taille maximale)</td>');
}
});
});
I have a menu that I walk with a "ng-repeat" to paint the problem that I have is that if you burn a variable with the json from the menu that is painted correctly, but if the menu as consumption from a WebAPI not paint me complete, menu is as if first paint the html consultation before the end of the WebAPI.
The menu paints me correctly, but a submenu (dropdown) does not paint me children.
They know how to solve it?
This is the menu
This is the html
<div ng-controller="dashboardController" class="nav-wrapper">
<ul ng-init="menuApp()">
<li ng-repeat="item in menus" ng-init="$last && rebindDropDowns()" class="{{item.Submenu.length ? 'dropdown-button' : ''}}" ng-bind-html="item.Nombre" data-activates="{{item.Submenu.length ? 'administracion' : ''}}">
{{item.Opcion}}
<ul ng-if="item.Submenu.length>0" id="administracion" class="dropdown-content">
<li ng-repeat="subItem in item.Submenu"><a ng-href="{{subItem.Nombre}}">{{subItem.Descripcion}}</a></li>
</ul>
</li>
</ul>
</div>
And this is the Controller
(function() {
'use strict';
angular.module('gastosDeViaje').controller('dashboardController', ['$scope', 'dashboardService', 'accesoService', 'notificaService', 'legalizacionService', '$location', '$q',
function($scope, dashboardService, accesoService, notificaService, legalizacionService, $location, $q, men) {
$scope.menuApp = function() {
accesoService.consultaMenu(accesoService.authentication.userName).then(function(result) {
$scope.menus = result.data;
console.log(result);
});
};
$scope.rebindDropDowns = function() {
console.log('entro drop');
$('.dropdown-button').dropdown();
};
$scope.menu = [{
"Opcion": "Solicitud",
"Nombre": "<i class=\"material-icons left\">flight</i>Solicitud ",
"Descripcion": "Formulario para Solicitud",
"Submenu": []
}, {
"Opcion": "Consultas",
"Nombre": "<i class=\"material-icons left\">search</i>Consultas ",
"Descripcion": "Formulario para Consultas",
"Submenu": []
}, {
"Opcion": "Transferencia",
"Nombre": "<i class=\"material-icons left\">attach_money</i>Transferencia ",
"Descripcion": "Transferencia",
"Submenu": []
}, {
"Opcion": "Administracion",
"Nombre": "<a class=\"dropdown-button\" data-activates=\"administracion\"><i class=\"material-icons left\">settings</i>Administracion<i class=\"material-icons right\">arrow_drop_down</i></a> ",
"Descripcion": "Menu de Administracion",
"Submenu": [{
"Opcion": "Reservas",
"Nombre": "#/reservas ",
"Descripcion": "Reservas",
"Submenu": null
}, {
"Opcion": "Globales",
"Nombre": "#/globales ",
"Descripcion": "Globales",
"Submenu": null
}, {
"Opcion": "Convenios",
"Nombre": "#/convenios ",
"Descripcion": "Convenios",
"Submenu": null
}, {
"Opcion": "Aplicacion",
"Nombre": "#/aplicacion ",
"Descripcion": "Aplicacion",
"Submenu": null
}]
}];
dashboardService.getEmpleadoAprobar(accesoService.authentication.userName).then(function(results) {
$scope.empleadosAprobar = results.data;
}, function() { //error
console.log('Error al Cargar los datos');
});
dashboardService.getEmpleadoAutorizar(accesoService.authentication.userName).then(function(results) {
$scope.empleadosAutorizar = results.data;
}, function() { //error
console.log('Error al cargar las autorizaciones');
});
dashboardService.getEmpleadolegalizar(accesoService.authentication.userName).then(function(results) {
$scope.empleadoLegalizar = results.data;
}, function() { //error
console.log('error al consultar');
});
dashboardService.getEmpleadoPdtLegalizarSub(accesoService.authentication.userName).then(function(results) {
$scope.PdtLegalizarSub = results.data;
}, function() {
console.log('Error al traer los pdtes por Legalizar');
});
dashboardService.getLegPdtAutorizar(accesoService.authentication.userName).then(function(result) {
$scope.LegPdtAutorizar = result.data;
}, function(error) {
console.log(error);
});
dashboardService.getLegPdtAprobar(accesoService.authentication.userName).then(function(result) {
$scope.LegPdtAprobar = result.data;
}, function(error) {
console.log(error);
});
dashboardService.getEmpleado(accesoService.authentication.userName).then(function(result) {
$scope.Nombre = result.data.Nombre;
}, function(error) {
if (!angular.isUndefined(error)) {
angular.forEach(error.data.ModelState.Model, function(errores) {
notificaService.error(errores);
});
}
});
dashboardService.solicitudesActivasEmpleado(accesoService.authentication.userName).then(function(result) {
$scope.solActivas = result.data;
});
/*$scope.solicitudesActivasEmpleado = function(){
console.log('entro activas');
$scope.pagActual = 0;
$scope.pageZise = 3;
$q.all([
dashboardService.solicitudesActivasEmpleado(accesoService.authentication.userName)
]).then(function(results){
$scope.solActivas = results[0].data;
$scope.numPaginas = function(){
return Math.ceil($scope.solActivas.length / $scope.pageZise);
};
}, function(error){
console.log(error);
});
};*/
$scope.CambiaEstadoSol = function(id, documento, estado) {
var parametros = '?id=' + id + '&documento=' + documento + '&estado=' + estado + '&funLog=' + accesoService.authentication.userName;
dashboardService.putCambiaEstadoSol(parametros).then(function() { //results
$location.path('#/dashboard'); //Lo hago para que me actualice la lista de pendientes x aprobar
if (estado === 'A') {
notificaService.success('Solicitud Aprobada Exitosamente');
}
if (estado === 'T') {
notificaService.success('Solicitud Autorizada Exitosamente');
/*if (documento==='L') {
//legalizacionService.postLegalizarAndres
}*/
}
if (estado === 'N') {
notificaService.success('Solicitud Anulada Exitosamente');
}
}, function(error) {
error.data.ModelState.Model.forEach(function(data) {
notificaService.error(data);
});
});
};
$scope.VerSolicitud = function(id) {
$location.path('/solicitud/' + id);
};
$scope.LegalizarSolicitud = function(id) {
$location.path('/legalizacion/' + id + '/' + 'L');
};
$scope.CambiaEstadoLeg = function(id) {
$location.path('/legalizacion/' + id + '/' + 'A');
};
}
]);
angular.module('gastosDeViaje').filter('paginacion', function() {
return function(input, start) {
if (!input || !input.length) {
return;
}
start = +start;
return input.slice(start);
};
});
})();
The problem seems to be on $('.dropdown-button').dropdown(); that is called from template in <li ng-repeat="item in menus" ng-init="$last && rebindDropDowns()"... but I can't simulate this issue.
It happens because ng-init is running before render html on DOM. Then when you apply jQuery plugin, the element doesn't exists yet.
By the way, using jQuery inside controller is not a good idea at all.
UPDATE 1
Try using a directive to initialize jQuery plugins like so:
angular.module('gastosDeViaje').directive('dropdownButton',
function() {
return {
restrict: 'EAC',
link: function($scope, element, attrs, controller) {
jQuery(element).dropdown();
}
};
}
);
This will apply directive for the class .dropdown-button.
I made this change and it worked: D
<div ng-controller="dashboardController" class="nav-wrapper">
<ul ng-init="menuApp()">
<li ng-repeat="item in menus" class="{{item.Submenu.length ? 'dropdown-button' : ''}}" ng-bind-html="item.Nombre" data-activates="{{item.Submenu.length ? 'administracion' : ''}}">
{{item.Opcion}}
<ul ng-if="item.Submenu.length>0" id="administracion" class="dropdown-content">
<li ng-repeat="subItem in item.Submenu" ng-init="$last && rebindDropDowns()">
<a ng-href="{{subItem.Nombre}}">{{subItem.Descripcion}}</a>
</li>
</ul></li></ul></div>