Carousel angular ui bootstrap 2.0.1 - javascript

I have a problem with the uib-carousel of angular-bootstrap 2.0.1.
I don't understand what happen... I had angular-bootstrap 2.0.0 with a slider with images and video (videogular directives). Everything was perfectly working, then I maj to 2.0.1 and since, nothing work...Even if I rollback to 2.0.0!!
The problem is that the slider doesn't change slide, nor if I click on the indicators, nor if I wait for the timer (set by myInterval).
Do you have an idea ?
Here is my HTML code:
<div uib-carousel active = "dv.active" interval = "dv.myInterval" no-wrap = "dv.noWrapSlides" class = "carousel-container" >
<div uib-slide ng-repeat = "slide in dv.slides track by slide.slide_id" index = "slide.slide_id" >
<div ng-if = "!slide.isVideo" >
<img ng-src = "{{slide.slide_path}}" title = "{{slide.nom_slide}}"
alt = "{{slide.nom_slide}}" width = "360" height = "280" style = "margin:auto;" >
</div >
<div ng-if = "slide.isVideo" >
<div class = "videogular-container" >
<videogular vg-theme = "slide.theme.url" vg-update-state = "dv.startStopSlideshow()" >
<vg-media vg-src = "slide.source" ></vg-media >
<vg-controls class = "vg-controls" vg-autohide = "slide.plugins.controls.autoHide"
vg-autohide-time = "slide.plugins.controls.autoHideTime" >
<vg-play-pause-button ></vg-play-pause-button >
<vg-time-display >{{ currentTime | date:'mm:ss':'+0000' }}</vg-time-display >
<vg-scrub-bar >
<vg-scrub-bar-current-time ></vg-scrub-bar-current-time >
</vg-scrub-bar >
<vg-time-display >{{ timeLeft | date:'mm:ss':'+0000' }}</vg-time-display >
<vg-time-display >{{ totalTime | date:'mm:ss':'+0000' }}</vg-time-display >
<vg-volume >
<vg-mute-button ></vg-mute-button >
<vg-volume-bar ></vg-volume-bar >
</vg-volume >
<vg-fullscreen-button ></vg-fullscreen-button >
</vg-controls >
<vg-overlay-play class = "overlay-play" ></vg-overlay-play >
<vg-poster vg-url = 'slide.plugins.poster' ></vg-poster >
<vg-buffering ></vg-buffering >
</videogular >
</div >
</div >
</div >
</div >
<!-- Indicators -->
<ol class = "custom-carousel-indicators" ng-show = "dv.slides.length > 1" >
<li ng-repeat = "slide in dv.slides track by $index" ng-class = " { active: dv.isActive(slide) }"
ng-click = " dv.setActive($index)" >
<img ng-src = "{{slide.slide_path}}" alt = "{{slide.nom_slide}}" width = "120px" height = "93px" >
</li >
</ol >
And here is my JavaScript:
$q.all([
services.getAllVideosFromMaterielId(mat_id).then(
function(dataVideos)
{
var videos = dataVideos.data;
for (var j = 0; j < videos.length; j ++) {
var slide = {
source : [
{
src: "assets/videos/materiel/" + videos[j]['video_path'], type: "video/mp4"
}
],
theme : {
url: "bower_components/videogular-themes-default/videogular.css"
},
plugin : {
controls: {
autoHide : true,
autoHideTime: 5000
},
poster : "assets/videos/posters/" + videos[j]['video_path']
},
slide_id : vm.slides.length,
//Pour les vidéos, slide_path correspond au chemin vers le poster de la vidéo
slide_path: "assets/videos/posters/" + videos[j]['video_path'] + ".png",
nom_slide : videos[j]['nom_video'],
legende : "",
isVideo : true
};
vm.slides.push(slide);
}
}
),
services.getAllImagesFromMaterielId(mat_id).then(
function(dataImages)
{
var images = dataImages.data;
for (var j = 0; j < images.length; j ++) {
var slide = {
slide_id : vm.slides.length,
slide_path: "assets/images/materiel/" + images[j]['image_path'],
nom_slide : images[j]['nom_image'],
legende : images[j]['legende_image'],
isVideo : false
};
vm.slides.push(slide);
}
}
)
]).then(function()
{
vm.myInterval = 5000;
vm.startStopSlideshow = function()
{
if (vm.myInterval == 5000) {
vm.myInterval = 0;
} else {
vm.myInterval = 5000;
}
};
vm.noWrapSlides = false;
vm.active = 0;
vm.isActive = function(slide)
{
return vm.active === slide.slide_id;
};
vm.setActive = function(idx)
{
vm.active = idx;
vm.slides[idx].active = true;
};
vm.noMateriel = false;
})
}
else {
vm.noMateriel = true;
}
Thanks a lot for the help!

Problem solved! It was just a compatibility problem with the update of bootstrap (and not angular-bootstrap as I thought)!
Downgrade to Bootstrap 3.3.7 solved the problem! :D

Related

How to add dot navigation to slider

I have a working slider that I would like to add dot navigation to. However I'm not quite sure how I can pull it off. I've tried to add my own jQuery to the code, but it just breaks the slider. Does anyone have a suggestion on how to add dot navigation to the bottom of this slider?
(function () {
function init(item) {
var items = item.querySelectorAll("li"),
current = 0,
autoUpdate = true,
timeTrans = 400000000;
//create nav
var nav = document.createElement("nav");
// nav.className = "nav_arrows";
//create button prev
var prevbtn = document.createElement("button");
prevbtn.className = "fp_go_prev_slide";
prevbtn.setAttribute("aria-label", "Prev");
//create button next
var nextbtn = document.createElement("button");
nextbtn.className = "fp_go_next_slide";
nextbtn.setAttribute("aria-label", "Next");
if (items.length > 1) {
nav.appendChild(prevbtn);
nav.appendChild(nextbtn);
item.appendChild(nav);
}
items[current].className = "current_slide";
if (items.length > 1) items[items.length - 1].className = "prev_slide";
if (items.length > 1) items[current + 1].className = "next_slide";
rightClick();
var navigate = function (dir) {
items[current].className = "current_slide";
if (dir === "right") {
current = current < items.length - 1 ? current + 1 : 0;
} else if (dir === "left") {
current = current > 0 ? current - 1 : items.length - 1;
} else {
current = current > 0 ? current - 1 : items.length - 1;
}
var nextCurrent = current < items.length - 1 ? current + 1 : 0,
prevCurrent = current > 0 ? current - 1 : items.length - 1;
items[current].className = "current_slide";
items[prevCurrent].className = "prev_slide";
items[nextCurrent].className = "next_slide";
if (dir === "right") {
rightClick();
}
if (dir === "left") {
leftClick();
}
};
item.addEventListener("mouseenter", function () {
autoUpdate = false;
});
item.addEventListener("mouseleave", function () {
rightClick();
autoUpdate = true;
});
setInterval(function () {
if (autoUpdate) navigate("right");
}, timeTrans);
prevbtn.addEventListener("click", function () {
navigate("left");
});
nextbtn.addEventListener("click", function () {
navigate("right");
});
function rightClick() {
var n = document.getElementsByClassName("next_slide");
var c = document.getElementsByClassName("current_slide");
var p = document.getElementsByClassName("prev_slide");
}
function leftClick() {
var n = document.getElementsByClassName("next_slide");
var c = document.getElementsByClassName("current_slide");
var p = document.getElementsByClassName("prev_slide");
}
}
[].slice
.call(document.querySelectorAll(".fp_slider_container_top_main"))
.forEach(function (item) {
init(item);
});
})();
And here's the html
<section class="featured-project-slider">
<div class="row fp-top-slider">
<div class="col-lg-8 fp-front-left">
<h1 class="fp-header extended-black-l">Featured Projects</h1>
</div>
<div class="col-lg-4 fp-front-right">
<button class="top-right-button extended-black-s">See all projects ></button>
</div>
<div class="col-lg-10 offset-lg-1 col-12 fp-center">
<!-- // * Slider starts -->
<section class="fp_slider_container_top_main">
<!-- all slides container starts -->
<ul class="fp_slider_container_top">
<?php $loop = new WP_Query(array('post_type' => 'project', 'cat' => '4', 'orderby' => 'ID', 'order' => 'ASC' )); ?>
<?php while ($loop->have_posts()): $loop->the_post(); ?>
<!-- slide starts -->
<li>
<div class="fp_slider_container_top_img_container">
<img src="<?php the_field('top_image'); ?>" alt="slider image" class="fp_slider_container_top_img"
loading="lazy">
<div class="fp-project-box">
<p class="fp-small extended-black-s">Our History</p>
<h1 class="condensed-semibold-l"><?php echo the_title(); ?></h1>
<p class="regular-m"><?php the_field('short_description'); ?></p>
<button class="extended-black-s">Learn More ></button>
</div>
</div>
</li>
<!-- slide ends -->
<?php endwhile;
wp_reset_query(); ?>
<?php
?>
</ul>
<!-- all slides container ends -->
</section>
<!-- // * Slider ends -->
</div>
<div class="col-lg-6 offset-lg-6 col-12 fp-front-right-red">
<div>
</div>
</section>

Play audio file based on id from mysql database

I have this audio player script that plays audio files, but i don't know how to play the files individually based on id from mysql database. I have a datatable and all the files listed there with a play button to make an idea. Thanks
Codepen audio player script:
https://codepen.io/abxlfazl/pen/YzGEVRP
Here is the audio script:
PHP:
<?php
$qnm = $db->query("SELECT * FROM `".RDCP_PREFIX."muzica` WHERE uid = ".$uid." ");
while ($row = $db->fetch($qnm)) {
$id = $row['mid']; // music id
$locatiem = $row['locatie'];
$numeclubs = $row['numeclub'];
$numecoregrafiem = $row['numecoregrafie'];
$piesa = str_replace("muzica/", "", $locatiem); // music file track
?>
HTML:
<div class="modal plyer fade delmusic<?php echo $id;?>" tabindex="-1" id="delmusic<?php echo $id; ?>"
track="<?php echo $id;?>" aria-labelledby="myDefaultModalLabel">
<div class="container" style="margin-top: 332px;display: flex;">
<div class="player">
<div class="player__header">
<div class="player__img player__img--absolute slider">
<button class="player__button player__button--absolute--nw playlist">
<img src="../../../dt/app-assets/images/elements/musicplayer/playlist.svg" alt="playlist-icon">
</button>
<button class="player__button player__button--absolute--center play">
<img src="../../../dt/app-assets/images/elements/musicplayer/play.svg" alt="play-icon">
<img src="../../../dt/app-assets/images/elements/musicplayer/pause.svg" alt="pause-icon">
</button>
<div class="slider__content">
<img class="img slider__img" src="http://physical-authority.surge.sh/imgs/1.jpg" alt="cover">
</div>
</div>
<div class="player__controls">
<button class="player__button back">
<img class="img" src="../../../dt/app-assets/images/elements/musicplayer/back.svg" alt="back-icon">
</button>
<p class="player__context slider__context">
<strong class="slider__name"></strong>
<span class="player__title slider__title"></span>
</p>
<button class="player__button next">
<img class="img" src="../../../dt/app-assets/images/elements/musicplayer/next.svg" alt="next-icon">
</button>
<div class="progres">
<div class="progres__filled"></div>
</div>
</div>
</div>
<ul class="player__playlist list">
<li class="player__song s<?php echo $id;?>">
<img class="player__img img" src="http://physical-authority.surge.sh/imgs/1.jpg" alt="cover">
<p class="player__context">
<b class="player__song-name"><?php echo $numecoregrafiem; ?></b>
<span class="flex">
<span class="player__title"><?php echo $numeclubs; ?></span>
</span>
</p>
<audio class="audio" src="<?php echo "dt/pagini/momente/momente/".$locatiem; ?>"></audio>
</li>
</ul>
</div>
</div>
</div>
Javascript:
const bgBody = ["#e5e7e9", "#ff4545", "#f8ded3", "#ffc382", "#f5eda6", "#ffcbdc", "#dcf3f3"];
const body = document.body;
const player = document.querySelector(".player");
const playerHeader = player.querySelector(".player__header");
const playerControls = player.querySelector(".player__controls");
const playerPlayList = player.querySelectorAll(".player__song");
const playerSongs = player.querySelectorAll(".audio");
const playButton = player.querySelector(".play");
const nextButton = player.querySelector(".next");
const backButton = player.querySelector(".back");
const playlistButton = player.querySelector(".playlist");
const slider = player.querySelector(".slider");
const sliderContext = player.querySelector(".slider__context");
const sliderName = sliderContext.querySelector(".slider__name");
const sliderTitle = sliderContext.querySelector(".slider__title");
const sliderContent = slider.querySelector(".slider__content");
const sliderContentLength = playerPlayList.length - 1;
const sliderWidth = 100;
let left = 0;
let count = 0;
let song = playerSongs[count];
let isPlay = false;
const pauseIcon = playButton.querySelector("img[alt = 'pause-icon']");
const playIcon = playButton.querySelector("img[alt = 'play-icon']");
const progres = player.querySelector(".progres");
const progresFilled = progres.querySelector(".progres__filled");
let isMove = false;
function closePlayer() {
playerHeader.classList.remove("open-header");
playerControls.classList.remove("move");
slider.classList.remove("open-slider");
}
function next(index) {
count = index || count;
if (count == sliderContentLength) {
count = count;
return;
}
left = (count + 1) * sliderWidth;
left = Math.min(left, (sliderContentLength) * sliderWidth);
sliderContent.style.transform = `translate3d(-${left}%, 0, 0)`;
count++;
run();
}
function back(index) {
count = index || count;
if (count == 0) {
count = count;
return;
}
left = (count - 1) * sliderWidth;
left = Math.max(0, left);
sliderContent.style.transform = `translate3d(-${left}%, 0, 0)`;
count--;
run();
}
function changeSliderContext() {
sliderContext.style.animationName = "opacity";
sliderName.textContent = playerPlayList[count].querySelector(".player__title").textContent;
sliderTitle.textContent = playerPlayList[count].querySelector(".player__song-name").textContent;
if (sliderName.textContent.length > 16) {
const textWrap = document.createElement("span");
textWrap.className = "text-wrap";
textWrap.innerHTML = sliderName.textContent + " " + sliderName.textContent;
sliderName.innerHTML = "";
sliderName.append(textWrap);
}
if (sliderTitle.textContent.length >= 18) {
const textWrap = document.createElement("span");
textWrap.className = "text-wrap";
textWrap.innerHTML = sliderTitle.textContent + " " + sliderTitle.textContent;
sliderTitle.innerHTML = "";
sliderTitle.append(textWrap);
}
}
function selectSong() {
song = playerSongs[count];
for (const item of playerSongs) {
if (item != song) {
item.pause();
item.currentTime = 0;
}
}
if (isPlay) song.play();
}
function run() {
changeSliderContext();
selectSong();
}
function playSong() {
if (song.paused) {
song.play();
playIcon.style.display = "none";
pauseIcon.style.display = "block";
}else{
song.pause();
isPlay = false;
playIcon.style.display = "";
pauseIcon.style.display = "";
}
}
function progresUpdate() {
const progresFilledWidth = (this.currentTime / this.duration) * 100 + "%";
progresFilled.style.width = progresFilledWidth;
if (isPlay && this.duration == this.currentTime) {
next();
}
if (count == sliderContentLength && song.currentTime == song.duration) {
playIcon.style.display = "block";
pauseIcon.style.display = "";
isPlay = false;
}
}
function scurb(e) {
// If we use e.offsetX, we have trouble setting the song time, when the mousemove is running
const currentTime = ( (e.clientX - progres.getBoundingClientRect().left) / progres.offsetWidth ) * song.duration;
song.currentTime = currentTime;
}
function durationSongs() {
let min = parseInt(this.duration / 60);
if (min < 10) min = "0" + min;
let sec = parseInt(this.duration % 60);
if (sec < 10) sec = "0" + sec;
const playerSongTime = `${min}:${sec}`;
}
changeSliderContext();
// add events
sliderContext.addEventListener("animationend", () => sliderContext.style.animationName ='');
playlistButton.addEventListener("click", closePlayer);
nextButton.addEventListener("click", () => {
next(0)
});
backButton.addEventListener("click", () => {
back(0)
});
playButton.addEventListener("click", () => {
isPlay = true;
playSong();
});
playerSongs.forEach(song => {
song.addEventListener("loadeddata" , durationSongs);
song.addEventListener("timeupdate" , progresUpdate);
});
progres.addEventListener("pointerdown", (e) => {
scurb(e);
isMove = true;
});
document.addEventListener("pointermove", (e) => {
if (isMove) {
scurb(e);
song.muted = true;
}
});
document.addEventListener("pointerup", () => {
isMove = false;
song.muted = false;
});
playerPlayList.forEach((item, index) => {
item.addEventListener("click", function() {
if (index > count) {
next(index - 1);
return;
}
if (index < count) {
back(index + 1);
return;
}
});
});
You could put the track ID into an attribute like "data-track" then retrieve it and send out an ajax request to a php page which will do your DB query and return the info you want.
// User selects track to play
$(".track").on('click', function(e){
track = $(this).data("track");
var data = {
trackId: track
};
$.ajax({
url: 'getTrack.php',
type: 'post',
data: data,
}).done(function(result){
// parse data from response and load your player's modal
}).fail(function(data){
// Uh-oh!
}).always(function(){
// Do something
});
});

Uncaught ReferenceError: Unable to process binding "visible: function (){return NeedPaging }" Message: NeedPaging is not defined

Uncaught ReferenceError: Unable to process binding "visible: function (){return NeedPaging }"
Message: NeedPaging is not defined
at visible (eval at parseBindingsString (knockout-3.4.2.js:68), :3:60)
at update (knockout-3.4.2.js:104)
at function.a.B.i (knockout-3.4.2.js:73)
at Function.Uc (knockout-3.4.2.js:52)
at Function.Vc (knockout-3.4.2.js:51)
at Function.U (knockout-3.4.2.js:51)
at Object.a.m.a.B (knockout-3.4.2.js:49)
at knockout-3.4.2.js:73
at Object.r (knockout-3.4.2.js:11)
at m (knockout-3.4.2.js:72)
I'm stuck any help would be great thank you in advance.
I'm only getting this error in production however in my local it is working just fine I'm not sure what I'm missing. It looks like the comment is being removed which is giving me the error.
$(function () {
"use strict";
var PagingVm = function (options) {
var self = this;
self.PageSize = ko.observable(options.pageSize);
self.CurrentPage = ko.observable(1);
self.TotalCount = ko.observable(options.totalCount);
self.PageCount = ko.pureComputed(function () {
return Math.ceil(self.TotalCount() / self.PageSize());
});
self.SetCurrentPage = function (page) {
if (page < self.FirstPage)
page = self.FirstPage;
if (page > self.LastPage())
page = self.LastPage();
self.CurrentPage(page);
};
self.FirstPage = 1;
self.LastPage = ko.pureComputed(function () {
return self.PageCount();
});
self.NextPage = ko.pureComputed(function () {
var next = self.CurrentPage() + 1;
if (next > self.LastPage())
return null;
return next;
});
self.PreviousPage = ko.pureComputed(function () {
var previous = self.CurrentPage() - 1;
if (previous < self.FirstPage)
return null;
return previous;
});
self.NeedPaging = ko.pureComputed(function () {
return self.PageCount() > 1;
});
self.NextPageActive = ko.pureComputed(function () {
return self.NextPage() != null;
});
self.PreviousPageActive = ko.pureComputed(function () {
return self.PreviousPage() != null;
});
self.LastPageActive = ko.pureComputed(function () {
return (self.LastPage() !== self.CurrentPage());
});
self.FirstPageActive = ko.pureComputed(function () {
return (self.FirstPage !== self.CurrentPage());
});
// this should be odd number always
var maxPageCount = 7;
self.generateAllPages = function () {
var pages = [];
for (var i = self.FirstPage; i <= self.LastPage(); i++)
pages.push(i);
return pages;
};
self.generateMaxPage = function () {
var current = self.CurrentPage();
var pageCount = self.PageCount();
var first = self.FirstPage;
var upperLimit = current + parseInt((maxPageCount - 1) / 2);
var downLimit = current - parseInt((maxPageCount - 1) / 2);
while (upperLimit > pageCount) {
upperLimit--;
if (downLimit > first)
downLimit--;
}
while (downLimit < first) {
downLimit++;
if (upperLimit < pageCount)
upperLimit++;
}
var pages = [];
for (var i = downLimit; i <= upperLimit; i++) {
pages.push(i);
}
return pages;
};
self.GetPages = ko.pureComputed(function () {
self.CurrentPage();
self.TotalCount();
if (self.PageCount() <= maxPageCount) {
return ko.observableArray(self.generateAllPages());
} else {
return ko.observableArray(self.generateMaxPage());
}
});
self.Update = function (e) {
self.TotalCount(e.TotalCount);
self.PageSize(e.PageSize);
self.SetCurrentPage(e.CurrentPage);
};
self.GoToPage = function (page) {
if (page >= self.FirstPage && page <= self.LastPage())
self.SetCurrentPage(page);
}
self.GoToFirst = function () {
self.SetCurrentPage(self.FirstPage);
};
self.GoToPrevious = function () {
var previous = self.PreviousPage();
if (previous != null)
self.SetCurrentPage(previous);
};
self.GoToNext = function () {
var next = self.NextPage();
if (next != null)
self.SetCurrentPage(next);
};
self.GoToLast = function () {
self.SetCurrentPage(self.LastPage());
};
}
var MainViewModel = function () {
var self = this;
self.PageSize = ko.observable(10);
self.AllData = ko.observableArray();
self.PagaData = ko.observableArray();
self.ActivePaging = ko.observable(false);
self.Paging = ko.observable(new PagingVm({
pageSize: self.PageSize(),
totalCount: self.AllData.length
}));
self.DeSelect = function (mainModel, event) {
if (event.target.value === self.SelectedSearchOption()) {
self.SelectedSearchOption(null);
event.target.checked = false;
}
return true;
};
self.pageSizeSubscription = self.PageSize.subscribe(function (newPageSize) {
self.Paging().Update({
PageSize: newPageSize,
TotalCount: self.AllData().length,
CurrentPage: self.Paging().CurrentPage()
});
self.RenderAgain();
});
self.currentPageSubscription = self.Paging().CurrentPage.subscribe(function () {
self.RenderAgain();
});
self.RenderAgain = function () {
var result = [];
var startIndex = (self.Paging().CurrentPage() - 1) * self.Paging().PageSize();
var endIndex = self.Paging().CurrentPage() * self.Paging().PageSize();
for (var i = startIndex; i < endIndex; i++) {
if (i < self.AllData().length)
result.push(self.AllData()[i]);
}
self.PagaData(result);
}
self.dispose = function () {
self.currentPageSubscription.dispose();
self.pageSizeSubscription.dispose();
}
}
var vm = new MainViewModel();
ko.applyBindings(vm);
vm.RenderAgain();
});
<div data-bind="visible: ActivePaging" class="row" style="display: none;">
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 form-group">
<label>page size</label>
<input class="form-control" type="number" min="1" data-bind="textInput:PageSize" />
</div>
<div class="col-sm-6">
<div class="form-group marg-top-reports">
<!-- ko with:Paging()-->
<ul data-bind="visible: NeedPaging" class="pull-left pagination">
<li data-bind="css: { disabled: !FirstPageActive() }">
<a data-bind="click: GoToFirst">First</a>
</li>
<li data-bind="css: { disabled: !PreviousPageActive() }">
<a data-bind="click: GoToPrevious">Previous</a>
</li>
<!-- ko foreach: GetPages() -->
<li data-bind="css: { active: $parent.CurrentPage() === $data }">
<a data-bind="click: $parent.GoToPage, text: $data"></a>
</li>
<!-- /ko -->
<li data-bind="css: { disabled: !NextPageActive() }">
<a data-bind="click: GoToNext">Next</a>
</li>
<li data-bind="css: { disabled: !LastPageActive() }">
<a data-bind="click: GoToLast">Last</a>
</li>
</ul>
<!-- /ko -->
</div>
</div>
</div>
</div>

AngularJS update chart from filter -> Infinite $digest loop

I would like to update a chart (made with angular-nvd3) each time some options are changed :
here are my options :
(in the code, it looks like this :
<input type="radio" ng-model="mode" value="actions"><strong ng-show="actions.length !== 0"> Actions :</strong><br />
<span class="retrait" ng-repeat = "action in actions">
<input type="checkbox" ng-model="actions[$index].value" ng-disabled="mode != 'actions'"> {{action.statut}}<br />
</span><br />
<input type="radio" ng-model="mode" value="jalons"><strong ng-show="jalons.length !== 0"> Jalons :</strong><br />
<span class="retrait" ng-repeat = "jalon in jalons">
<input type="checkbox" ng-model="jalons[$index].value" ng-disabled="mode != 'jalons'"> {{jalon.statut}}<br />
</span><br />
First, i tried to make a filter, but my filter had to access scope values (to see what options were checked), so i had to use "this" into the filter. The issue is that when updating the graph, it changes the model and re-lauches the filter : it makes an infinite loop.
So I decided to make, a pseudo filter, with a function in the controller.
Here is my function :
$scope.generateData = function() {
var liste = [];
var i, j, k, n, p, dataStock;
dataStock = [
{"key":{'jalons':'Non atteint', 'actions':'Non fait', 'phases':'Non fait'}[$scope.mode],"values":[]},
{"key":{'jalons':'Atteint', 'actions':'En cours', 'phases':'En cours'}[$scope.mode],"values":[]},
{"key":{'jalons':'Validé', 'actions':'Fait', 'phases':'Fait'}[$scope.mode],"values":[]}
];
var stock_retards_ouverture = [];
var stock_retards_fermeture = [];
var flux_retards_ouverture = [];
var flux_retards_fermeture = [];
var stock_non_faite = [];
var stock_faite = [];
var stock_en_cours = [];
var flux_non_faite = [];
var flux_faite = [];
var flux_en_cours = [];
var num_serie = parseInt($scope.serie.substring($scope.serie.length-1, $scope.serie.length), 10);
i=1;
while(i<=num_serie) {
stock_retards_ouverture.push(0);
stock_retards_fermeture.push(0);
flux_retards_ouverture.push(0);
flux_retards_fermeture.push(0);
stock_non_faite.push(0); // pour les jalons, c'est le statut non atteint
stock_faite.push(0); // pour les jalons, validé
stock_en_cours.push(0); // pour les jalons, atteint
flux_non_faite.push(0);
flux_faite.push(0);
flux_en_cours.push(0);
i+=1;
}
for(i = 0; i<$scope.raw_data.length; i++) {
var element = $scope.raw_data[i];
var type = element.type;
var root = element.root;
var statut = element[$scope.serie].statut;
// pour les phases
if($scope.mode === 'phases') {
if(type == $scope.sauvegarde.taches_types.phase) {
for(j = 0; j< $scope.phases.length; j++) {
if($scope.phases[j].statut == statut && $scope.phases[j].value === true) {
for(k = 0; k<$scope.affichage.length;k++){
if(root == $scope.affichage[k].projet && $scope.affichage[k].value === true){
liste.push(element);
// pour chaque série
for(p=1;p<=num_serie;p++) {
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.phase_en_cours) {
stock_en_cours[p-1] += 1;
}
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.phase_faite) {
stock_faite[p-1] += 1;
}
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.phase_non_faite) {
stock_non_faite[p-1] += 1;
}
}
}
}
}
}
}
}
// pour les actions
if($scope.mode === 'actions') {
if(type == $scope.sauvegarde.taches_types.action) {
for(j = 0; j< $scope.actions.length; j++) {
if($scope.actions[j].statut == statut && $scope.actions[j].value === true) {
for(k = 0; k<$scope.affichage.length;k++){
if(root == $scope.affichage[k].projet && $scope.affichage[k].value === true){
liste.push(element);
// pour chaque série
for(p=1;p<=num_serie;p++) {
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.action_en_cours) {
stock_en_cours[p-1] += 1;
}
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.action_faite) {
stock_faite[p-1] += 1;
}
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.action_non_faite) {
stock_non_faite[p-1] += 1;
}
}
}
}
}
}
}
}
// pour les jalons
if($scope.mode === 'jalons') {
if(type == $scope.sauvegarde.taches_types.jalon) {
for(j = 0; j< $scope.jalons.length; j++) {
if($scope.jalons[j].statut == statut && $scope.jalons[j].value === true) {
for(k = 0; k<$scope.affichage.length;k++){
if(root == $scope.affichage[k].projet && $scope.affichage[k].value === true){
liste.push(element);
// pour chaque série
for(p=1;p<=num_serie;p++) {
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.jalon_atteint) {
stock_en_cours[p-1] += 1;
}
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.jalon_valide) {
stock_faite[p-1] += 1;
}
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.jalon_non_atteint) {
stock_non_faite[p-1] += 1;
}
}
}
}
}
}
}
}
}
$scope.stock_retards_ouverture = stock_retards_ouverture;
$scope.stock_retards_fermeture = stock_retards_fermeture;
$scope.flux_retards_ouverture = flux_retards_ouverture;
$scope.flux_retards_fermeture = flux_retards_fermeture;
$scope.stock_non_faite = stock_non_faite;
$scope.stock_faite = stock_faite;
$scope.stock_en_cours = stock_en_cours;
$scope.flux_non_faite = flux_non_faite;
$scope.flux_faite= flux_faite;
$scope.flux_en_cours = flux_en_cours;
for(i=0;i<num_serie;i++) {
var lastElem1 = {};
var lastElem2 = {};
var lastElem3 = {};
if(dataStock[0].values.length === 0) {
lastElem1.y1 = 0;
lastElem2.y1 = 0;
lastElem3.y1 = 0;
} else {
lastElem1 = dataStock[0].values[dataStock[0].values.length - 1];
lastElem2 = dataStock[1].values[dataStock[1].values.length - 1];
lastElem3 = dataStock[2].values[dataStock[2].values.length - 1];
}
var elem0 = {
x: "serie"+(i+1),
y: stock_faite[i],
y0: lastElem1.y1,
series: i,
size: stock_faite[i],
y1: lastElem1.y1 + stock_faite[i]
};
var elem1 = {
x: "serie"+(i+1),
y: stock_en_cours[i],
y0: lastElem2.y1,
series: i,
size: stock_en_cours[i],
y1: lastElem2.y1 + stock_en_cours[i]
};
var elem2 = {
x: "serie"+(i+1),
y: stock_non_faite[i],
y0: lastElem3.y1,
series: i,
size: stock_non_faite[i],
y1: lastElem3.y1 + stock_non_faite[i]
};
dataStock[0].values.push(elem0);
dataStock[1].values.push(elem1);
dataStock[2].values.push(elem2);
}
return dataStock;
};
It generates the proper data, which can be used to create the graph.
Then, for the graph, I used the awesome library Angular-nvd3 :
<div class="graphCtrl" id="graph1">
<h3 class="graphTitle">Suivi des actions (Stock)</h3>
<nvd3 options="options" data="generateData()"></nvd3>
</div>
Where get the data from my function.
But I don't get why, I still have the infinite loop of $digest, as I can still see the issue :
Error: [$rootScope:infdig]
Do you know where it could come from ?
I think the problem is here
<div class="graphCtrl" id="graph1">
<h3 class="graphTitle">Suivi des actions (Stock)</h3>
<nvd3 options="options" data="generateData()"></nvd3>
</div>
you see, every time the $digest process runs the function will be executed and this function will change model which triggers $digest and so on, that's your infinite loop, best to do is to assign generated data to variable and use it then in html
<div class="graphCtrl" id="graph1">
<h3 class="graphTitle">Suivi des actions (Stock)</h3>
<nvd3 options="options" data="myGeneratedData"></nvd3>
</div>
js
$scope.myGeneratedData = $scope.generateData()
or just generatedData() as it doesn't have to be on $scope

How to give Input tag attribute type button value at Runtime in Meteor JS

How to give Input tag Attribute type button value at Runtime in Meteor JS as shown below:
newButton = document.createElement('input');
newButton.value = ''; - Here value i need like as i.e , val ="{{btnValue}}"
I'm not familiar with Meteor JS, so please offer any suggestions.
Html Code I need like as below in Runtime JS:
// Manually Creating button
<input type="button" id="no" val ="{{btnValue}}">
My HTML Code :
<head>
<title>TICTACTOE App 1.3</title>
</head>
<body>
{{> uname}}
{{> main}}
{{> games }}
</body>
<template name="uname">
<h1>Welcome to TICTACTOE App</h1>
<p id="pname"><b>User Name :</b> <input type="text" id="uname" ></p>
</template>
<template name="main">
<p id="pno"><b>Layout Number :</b> <input type="text" id="no" ></p>
<div name="main"></div>
</template>
<template name="games">
{{#each game}}
<div>{{turn}} </div>
<div> {{wturn}}</div>
<div>{{bval}}</div>
{{/each}}
</template>
Meteor JS:
Counts = new Meteor.Collection('count');
TurnData= new Meteor.Collection('tdata');
BtnValues= new Meteor.Collection('btnvalues');
var x = "X";
var o = "O";
var Whoseturn = "";
var no;
var newButton;
var count = 0;
var IsWin = false;
var IsTurn = true;
var val = "";
var ButtonValue= "";
var btnval;
if (Meteor.isClient)
{
Template.main.helpers
({
btnValue: function()
{
return BtnValues.findOne();
}
});
Template.main.events
({
'click input' : function ()
{
// template data, if any, is available in 'this'
var name = document.getElementById('uname');
console.log(name.value);
var btnid = event.currentTarget.id;
ButtonValue = btnid;
btnval = document.getElementById(btnid);
console.log(btnid);
if(btnval.value == '' && btnid != "no" )
{
calculateTurn();
console.log(Whoseturn);
btnval.value = Whoseturn;
var myBtnData = BtnValues.findOne();
BtnValues.update( {_id: myBtnData._id},{ $set:{bval : btnval} });
}
}
});
Template.main.events
({
'keydown input#no' : function ()
{
// template data, if any, is available in 'this'
if (event.which == 13)
{
// 13 is the enter key event
console.log("You pressed enter key");
no = document.getElementById('no');
count = 0;
var myTurnData = Counts.findOne();
Counts.update( {_id: myTurnData._id},{ $set:{turn : count } });
if(no.value != '')
{
document.getElementById('pname').style.visibility = 'hidden';
document.getElementById('pno').style.visibility = 'hidden';
UI();
}
}
}
});
}
function UI()
{
console.log("*** UI() ***");
for(var i = 1 ; i <= no.value ; i++)
{
//var body=document.getElementsByTagName('body')[0];
var body = document.getElementsByName('main')[0];
for(var j = 1 ; j <= no.value ; j++)
{
newButton = document.createElement('input');
newButton.type = 'button';
newButton.id = 'btn'+i+j;
newButton.value = '';////Here value i need like as val ="{{btnValue}}
body.appendChild(newButton);
}
var newline = document.createElement('br');
body.appendChild(newline) ;
}
}
function calculateTurn()
{
var myTurnData = Counts.findOne();
count = myTurnData.turn;
console.log("count="+count);
count = count + 1;
console.log("updated count="+count);
Counts.update( {_id: myTurnData._id},{ $set:{turn : count } });
if(count <= 9)
{
var TData = TurnData.findOne();
IsTurn = true;
if(count % 2 == 0)
{
Whoseturn = o ;
TurnData.update( {_id: TData._id},{ $set:{wturn : Whoseturn } });
}
else
{
Whoseturn = x ;
TurnData.update( {_id: TData._id},{ $set:{wturn : Whoseturn } });
}
}
else
{
IsTurn = false;
console.log(" >= 9");
}
}
if (Meteor.isServer)
{
Meteor.startup(function ()
{
// code to run on server at startup
Counts.insert({turn : count});
TurnData.insert({wturn : Whoseturn});
BtnValues.insert({bval : val});
});
}

Categories