Bootstrap switch inside datatables plugin with ajax call catch event - javascript

I'm using datatables plugin and I have a problem with bootstrap switch.
This is my javascript code, where I create a switch with the value retrieved from ajax call:
$(document).ready(function() {
if ( ! $.fn.DataTable.isDataTable( '#usersTable' ) ) {
userTable = $('#usersTable').DataTable({
responsive: true,
//fix problem with responsive table
"autoWidth": false,
"ajax": "table",
"columns": [
{ "data": "username" },
{ data: "enabled", render: function ( data, type, row ) {
if (data) {
return '<input data="username" type="checkbox" name="my-checkbox" checked>';
}
else {
return '<input data="username" type="checkbox" name="my-checkbox">';
}
}
},
{ "data": "role.role"},
{ "data": "clientVersion.name" },
{
data: null,
className: "center",
defaultContent: '<button type="button" class="btn btn-danger" id="deleteLicense" data-toggle="modal" th:attr="data-href=${license.idClientLicense}" data-target="#deleteLicenseModal">Delete</button>'
}
],
"fnDrawCallback": function() {
//Initialize checkbos for enable/disable user
$("[name='my-checkbox']").bootstrapSwitch({size: "small", onColor:"success", offColor:"danger"});
}
});
}
else {
userTable.ajax.url("table").load();
}
$('input[name="my-checkbox"]').on('switchChange.bootstrapSwitch', function(event, state) {
//CSRF attribute for spring security
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$.ajax({
type : "POST",
url : "status"+(this).attr("data"),
data : form.serialize(),
beforeSend:function(xhr) {
xhr.setRequestHeader(header, token);
},
// all right with rest call
success : function(data) {
// No exception occurred
if (data.status==true){
// Also the field are right(for e.g. form value)
if(data.success==true){
// il risultato sta in data.result
// window.location.reload(true);
//reset select 2 choise because it can set with old user who no longer exist
// reload only the tag with id carsTable, so only the table
}
else{
// code if there are some error into form for example
}
} else {
// code exception
notifyMessage(data.result, 'error');
}
},
// error during rest call
error : function(data) {
window.location.href = "/ATS/500";
}
});
});
});
and this is HTML code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Administration users</title>
<!-- Tell the browser to be responsive to screen width -->
<meta
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
name="viewport">
<!-- Spring csrf -->
<meta name="_csrf" th:content="${_csrf.token}" />
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" th:content="${_csrf.headerName}" />
<!-- Bootstrap Core CSS -->
<link th:href="#{/static/assets/bootstrap/css/bootstrap.css}"
rel="stylesheet">
<!-- Font Awesome -->
<link rel="stylesheet"
th:href="#{/static/assets/component/font-awesome-4.4.0/css/font-awesome.min.css}">
<!-- Ionicons -->
<link rel="stylesheet"
href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<!-- DataTables -->
<link rel="stylesheet"
th:href="#{/static/assets/plugins/datatables/dataTables.bootstrap.css}">
<link rel="stylesheet"
th:href="#{/static/assets/plugins/datatables/extensions/Responsive/css/responsive.bootstrap.min.css}">
<!-- Theme style -->
<link rel="stylesheet"
th:href="#{/static/assets/dist/css/AdminLTE.min.css}">
<!-- AdminLTE Skins. Choose a skin from the css/skins
folder instead of downloading all of them to reduce the load. -->
<link rel="stylesheet"
th:href="#{/static/assets/dist/css/skins/_all-skins.min.css}">
<!-- Select2 -->
<link rel="stylesheet"
th:href="#{/static/assets/plugins/select2/select2.min.css}">
<!-- Bootstrap switch -->
<link rel="stylesheet"
th:href="#{/static/assets/plugins/bootstrap-switch/css/bootstrap-switch.min.css}">
<!-- jQuery 2.1.4 -->
<script th:src="#{/static/assets/plugins/jQuery/jQuery-2.1.4.min.js}"
type="text/javascript"></script>
<!-- Bootstrap 3.3.5 -->
<script th:src="#{/static/assets/bootstrap/js/bootstrap.min.js}"
type="text/javascript"></script>
<!-- DataTables -->
<script type="text/javascript"
th:src="#{/static/assets/plugins/datatables/jquery.dataTables.min.js}"></script>
<script type="text/javascript"
th:src="#{/static/assets/plugins/datatables/dataTables.bootstrap.min.js}"></script>
<script type="text/javascript"
th:src="#{/static/assets/plugins/datatables/extensions/Responsive/js/dataTables.responsive.min.js}"></script>
<script type="text/javascript"
th:src="#{/static/assets/plugins/datatables/extensions/Responsive/js/responsive.bootstrap.min.js}"></script>
<!-- page script -->
<!-- Slimscroll -->
<script type="text/javascript"
th:src="#{/static/assets/plugins/slimScroll/jquery.slimscroll.min.js}"></script>
<!-- FastClick -->
<script type="text/javascript"
th:src="#{/static/assets/plugins/fastclick/fastclick.min.js}"></script>
<!-- Bootstrap-growl -->
<script type="text/javascript"
th:src="#{/static/assets/plugins/notify/jquery.bootstrap-growl.js}"></script>
<!-- AdminLTE App -->
<script type="text/javascript"
th:src="#{/static/assets/dist/js/app.min.js}"></script>
<!-- AdminLTE for demo purposes -->
<script type="text/javascript"
th:src="#{/static/assets/dist/js/demo.js}"></script>
<!-- Select2 -->
<script type="text/javascript"
th:src="#{/static/assets/plugins/select2/select2.full.min.js}"></script>
<!-- Bootstrap switch -->
<script type="text/javascript"
th:src="#{/static/assets/plugins/bootstrap-switch/js/bootstrap-switch.min.js}"></script>
<script type="text/javascript" th:src="#{/static/assets/js/user.js}"></script>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<!-- Header nd menu fragment -->
<div th:replace="../fragments/dashboard-header :: dashboard-header"></div>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>Administration</h1>
<ol class="breadcrumb">
<li><a th:href="#{/}"><i class="fa fa-dashboard"></i> Home
</a></li>
<li class="active">User</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">Users</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<!-- -Users table -->
<table id="usersTable"
class="table table-bordered table-striped">
<thead>
<tr>
<th>Username</th>
<th>Enable</th>
<th>Role</th>
<th>Version</th>
<th>Delete</th>
</tr>
</thead>
</table>
<!-- Create two equals button because when I am on desktop I show the text add fleet otherwise the + and the tooltip.
This is need because otherwise the text goes out the button -->
<button id="addUserButton" type="button"
class="btn btn-primary visible-lg col-lg-1 col-lg-offset-11"
data-toggle="modal" data-target="#addUserModal">Add
user</button>
<button id="addlicenseButton" type="button"
class="btn btn-primary hidden-lg col-xs-1 col-xs-offset-11"
data-toggle="modal" data-target="#addUserModal">
<span class="glyphicon glyphicon-plus" data-toggle="tooltip"
title="Add user"></span>
</button>
</div>
</div>
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
</div>
</body>
</html>
I read several questions and answer but I think that my problem is linked to "fnDrawCallback": function() because I tried all the solutions and None worked. Might be that the switch isn't correctly setted?
This is the table

CAUSE
Pages other than first do not exist in DOM at the time of initialization, that is why your handler never gets called.
SOLUTION
You need to use event delegation by providing selector as a second argument in on() call, see example below:
$('#usersTable').on('switchChange.bootstrapSwitch', 'input[name="my-checkbox"]', function(event, state) {
// ... skipped ...
});
From jQuery on() method documentation:
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time.
See "Direct and delegated events" in jQuery on() method documentation and jQuery DataTables – Why click event handler does not work for more information.
NOTES
Custom controls and Responsive extension require special handling. If column containing custom control becomes hidden or visible, it should be re-initialized. See jQuery DataTables – Responsive extension and custom controls for more information.

Related

select tag created in ajax request doesn't be shown in HTML file

I want to load some options via ajax request and show them into select tag HTML. After I get data and create a select tag manually, the HTML file doesn't show the select tag. I used jquery and put the codes in other files.
I try to put ajax request in both $(document).ready() and function but it doesn't work.
<!DOCTYPE html>
<html lang="en">
<head>
<!-- META SECTION -->
<title>Atlant - Responsive Bootstrap Admin Template</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="icon" href="favicon.ico" type="image/x-icon"/>
<!-- END META SECTION -->
<!-- CSS INCLUDE -->
<link rel="stylesheet" type="text/css" id="theme" href="/public/css/theme-default.css"/>
<!-- EOF CSS INCLUDE -->
</head>
<body onload="onLoadCenterName()">
<!-- START PAGE CONTAINER -->
<div class="page-container">
<!-- PAGE CONTENT -->
<div class="page-content ">
<!-- PAGE CONTENT WRAPPER -->
<div class="page-content-wrap">
<div class="row">
<div class="col-md-12">
<form id="addSiteForm" class="form-horizontal"
style="margin-top: 20px;margin-left: 50px;margin-right: 50px">
<div class="panel panel-default">
<div class="panel-heading ">
<h3 class="panel-title "><strong>Add New Site</strong></h3>
</div>
<div class="panel-body">
</div>
<div class="panel-body">
<div class="form-group">
<label class="col-md-3 col-xs-12 control-label">Select User Type</label>
<div class="col-md-6 col-xs-12">
<select id="addSiteSelectCenterInput" class="form-control select">
</select>
<span class="help-block">Select type of the user account </span>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- END PAGE CONTENT WRAPPER -->
</div>
<!-- END PAGE CONTENT -->
</div>
<!-- END PAGE CONTAINER -->
<!-- START PRELOADS -->
<audio id="audio-alert" src="/public/audio/alert.mp3" preload="auto"></audio>
<audio id="audio-fail" src="/public/audio/fail.mp3" preload="auto"></audio>
<!-- END PRELOADS -->
<!-- START SCRIPTS -->
<!-- START PLUGINS -->
<script type="text/javascript" src="/public/js/plugins/jquery/jquery.min.js"></script>
<script type="text/javascript" src="/public/js/plugins/jquery/jquery-ui.min.js"></script>
<script type="text/javascript" src="/public/js/plugins/bootstrap/bootstrap.min.js"></script>
<!-- END PLUGINS -->
<!-- START THIS PAGE PLUGINS-->
<script type='text/javascript' src='/public/js/plugins/icheck.js'></script>
<script type="text/javascript" src="/public/js/plugins/jquery/jquery.mCustomScrollbar.js"></script>
<!-- END THIS PAGE PLUGINS-->
<!-- START TEMPLATE -->
<!-- <script type="text/javascript" src="/public/js/settings.js"></script>-->
<script type='text/javascript'
src='/public/js/plugins/validationengine/languages/jquery.validationEngine-en.js'></script>
<script type='text/javascript' src='/public/js/plugins/validationengine/jquery.validationEngine.js'></script>
<script type="text/javascript" src="/public/js/plugins/bootstrap/bootstrap-select.js"></script>
<script type='text/javascript' src='/public/js/plugins/noty/jquery.noty.js'></script>
<script type='text/javascript' src='/public/js/plugins/noty/layouts/topCenter.js'></script>
<script type='text/javascript' src='/public/js/plugins/noty/layouts/topLeft.js'></script>
<script type='text/javascript' src='/public/js/plugins/noty/layouts/topRight.js'></script>
<script type='text/javascript' src='/public/js/plugins/noty/themes/default.js'></script>
<script type="text/javascript" src="/public/js/plugins.js"></script>
<script type="text/javascript" src="/public/js/actions.js"></script>
<script type="text/javascript" src="/public/js/addSite.js"></script>
<!-- END TEMPLATE -->
<!-- END SCRIPTS -->
</body>
</html>
addSite.js
function onLoadCenterName() {
$.ajax({
type: 'GET',
url: '/centers/getAllCenters',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
console.log("SUCCESS : ", data);
let selectList = document.getElementById("addSiteSelectCenterInput");
$.each(data, function (key, value) {
console.log(key, value._id, value.centerName);
const option = document.createElement("option");
option.value = value._id;
option.text = value.centerName;
selectList.appendChild(option);
// $('#addSiteSelectCenterInput')
// .append($("<option></option>")
// .attr("value", )
// .text(value.centerName));
});
console.log(selectList);
noty({
text: 'Successful load centers ',
layout: 'topRight',
type: 'success',
timeout: true
}).setTimeout(5000);
$.mpb("update", {
value: 100, speed: 5, complete: function () {
$(".mpb").fadeOut(200, function () {
$(this).remove();
});
}
});
},
error: function (e) {
console.log("ERROR : ", e);
noty({
text: 'There was an error',
layout: 'topRight',
type: 'error',
timeout: true
}).setTimeout(5000);
$.mpb("update", {
value: 100, speed: 5, complete: function () {
$(".mpb").fadeOut(200, function () {
$(this).remove();
});
}
});
}
});
}
in chrom console, result is here:
<select id="addSiteSelectCenterInput" class="form-control select" style="display: none;">
<option value="5d0f86f0a2b7a41bdcd3c91f">sdf</option><option value="5d0f9c4067731820fcabf1eb">scaasdad</option></select>
According to your console result, the <select> is not visible because it has the attribute style="display: none;".
There is nothing in the code that you have provided that would add that attribute, so you obviously haven't given us all the relevant code.
So you either need to remove that attribute... or don't hide the control in the first place.
To show it via jQuery use .show()...
$("#addSiteSelectCenterInput").show()
Or in vanilla JS change the style.display property...
document.getElementById("addSiteSelectCenterInput").style.display = "";

I want to add an event handler on a button that will make a component display with Vue.js 2.0

I want to add an eventhandler on my component. When I click the button I want the component to show. I tried all kinds of solutions but I think my knowledge is lacking. Here is my code, I would be thankful for help. Feel free to explain what the best methods are for solving this problem and how I should think in scenarios like these. Appricitate your time.
HTML
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<link rel="stylesheet" href="main.css">
<title>SneakPeak</title>
</head>
<body>
<div id="body-div">
<div id="app">
<modal-button></modal-button>
<modal-1 v-if="modalStatus == 2"></modal-1>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<!-- development version, includes helpful console warnings -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="app.js"></script>
</div>
</body>
</html>
JAVASCRIPT
// Define a new component called button-counter
Vue.component('modal-button', {
data: function () {
return {
count: 0,
}
},
template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
// Defining a component called modal-1
Vue.component('modal-1', {
props: ["sModal"],
template: `
<transition name="modal">
<div class="modal-mask">
<div class="modal-wrapper">
<div class="modal-container">
<div class="modal-header">
<slot name="header"
default header
</slot>
</div>
<div class="modal-body">
<slot name="body">
default body
</slot>
</div>
<div class="modal-footer">
<slot name="footer">
default footer
<button class="modal-default-button" #click="$emit('close')">
OK
</button>
</slot>
</div>
</div>
</div>
</div>
</transition>
`
})
var shaba = new Vue({
el: '#app',
props: ["sModal"],
data: {
modalStatus: 0
},
})
// // register modal component
// Vue.component('modal', {
// template: modalTemplate
// })
// // start app
// new Vue({
// el: '#body-div',
// data: {
// showModal: false
// }
// })
Old Answer:
if you want to show/hide your component on click then use #click="val = !val" on the button component and use v-if or v-show="val" on the modal componant to enable/ disable Display.
set val: false in your data.
New Answer:
Looks Like you button is already capturing click so please follow this pen https://codepen.io/ashwinbande/pen/WPozgR
what we are doing is on button click executing a method which increments count as well as emits a custom event. In button component on that event, we change the value of val. then the val is used to show hide the modal component`!

AngularJS Message Display On Click

I have two questions
How to display the initial message and/or upon button click. The current code I have displays the message continuously. I want it to display initially and once users starts pressing other button I want the message "Start guessing" to disappear and only appear after user clicks Start Over button.
How to display the correct answer when user clicks on Give up.
HTML
<!DOCTYPE html>
<html lang="en" data-ng-app="myApp">
<head>
<title>Template that uses Bootstrap</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initialscale=1.0"/>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet" />
<!-- Custom CSS -->
<link href="css/custom.css" rel="stylesheet" />
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div data-ng-controller="myCtrl">
<div class="container">
<h1>Guessing Game</h1><br>
<label>Enter Guess:</label>
<input type="text" id="guess" name="guess" data-ng-model="guess"/><br>
<span data-ng-bind="Message"></span>
<div class="row">
<div class="col-md-12">
<button class="btn btn-primary btn-md" data-ng-click="checkGuess()">Check</button>
<button class="btn btn-warning btn-md" data-ng-click="showAnswer()">Give Up</button>
<button class="btn btn-info btn-md" data-ng-click="startGame()">Start Over</button>
</div></div>
<div class="row">
<div class="col-xs-7">
<div ng-show="deviation<0" class="alert alert-warning">Guess higher</div>
<div ng-show="deviation>0" class="alert alert-warning">Guess lower</div>
<div ng-show="deviation===0" class="alert alert-success">You got it!</div>
</div></div>
</div>
</div>
<!-- jQuery – required for Bootstrap's JavaScript plugins) -->
<script src="js/jquery.min.js"></script>
<!-- All Bootstrap plug-ins file -->
<script src="js/bootstrap.min.js"></script>
<!-- Basic AngularJS -->
<script src="js/angular.min.js"></script>
<!-- Your Controller -->
<script src="js/app.js"></script>
</body>
</html>
Angular
/*global angular */
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function ($scope) {
"use strict";
$scope.checkGuess = function () {
$scope.deviation = $scope.original - $scope.guess;
};
$scope.startGame = function () {
$scope.guess = null;
$scope.original = Math.floor(Math.random() * 1000 + 1);
$scope.deviation = null;
$scope.display = false;
$scope.Message = "Start guessing.";
};
$scope.showAnswer = function () {
$scope.original = Math.floor(Math.random() * 1000 + 1);
$scope.display = true;
};
$scope.startGame();
}
);
1) Use ng-hide to hide your element when needed:
<span data-ng-bind="Message" ng-hide="hideMessage"></span>
In the checkGuess and showAnswer functions set the hideMessage to true:
$scope.hideMessage = true;
In the startGame function, set it to false:
$scope.hideMessage = false;
2) In your HTML add a tag:
<div ng-show="showOriginal">{{previousOriginal}}</div>
And in your showAnser and startGame function, add:
$scope.showOriginal = true;
$scope.previousOriginal = angular.copy($scope.original);
And remove of the showAnswer function:
$scope.original = Math.floor(Math.random() * 1000 + 1)
Finally, in the startGame function, set it to false:
$scope.showOriginal = false;

Angularjs fails to dynamic change image src

Hello i'm building an application where i want to dynamically change the source of an image in order to force reload it . The problem is that in order of this i only get a broken image on the browser. Instead , if a run the function manually by a button it runs perfect .
HTML document
<!DOCTYPE html>
<html lang="en" ng-app='cameraApp'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Node JS Camera</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src='https://code.angularjs.org/1.4.4/angular-sanitize.min.js'></script>
<script src="cameraApp.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="jumbotron">
<h1>Welcome to NodeJS Camera v1</h1>
</div>
<div ng-controller="HomeController">
<div class="cameraControl col-md-5">
<p>Here is the camera control</p>
<button class="btn btn-default" ng-click="getSnapshot()">Snapshot</button>
<button class="btn btn-info" ng-click="intervalFunction()">Start Feed</button>
</div>
<div class="lifeFeed col-md-7">
<p>Here is the live feed</p>
<p><button class="btn btn-default" ng-click="readSnapshot()">Snapshot Read</button></p>
<img width='600' height='600' ng-src="{{snapshot}}" alt="SnapShot taken">
</div>
</div>
</div>
</body>
</html>
cameraApp.js
var cameraApp = angular.module('cameraApp',[]);
cameraApp.controller('HomeController', function($scope,$http,$timeout) {
function updateImage() {
var img = 'snapshots/camera.jpg'+ '?decache=' + Math.random();
console.log('Snapshot Loaded');
$scope.snapshot = img;
};
$scope.readSnapshot = updateImage;
$scope.getSnapshot = function() {
$http.get('/api/getSnapshot')
.then(function(response) {
// this callback will be called asynchronously
// when the response is available
console.log('Snapshot captured');
$scope.readSnapshot();
}, function(response) {
console.log('Error in capturing...');
});
}
$scope.intervalFunction = function() {
$timeout(function() {
$scope.getSnapshot();
$scope.intervalFunction();
}, 2000);
};
// Kick off the interval
$scope.intervalFunction();
});
There are two solutions I've used for this in the past.
1) Use an ng-if/ng-show on your img tag. This will prevent the broken image from displaying.
<img ng-if='snapshot'>
2) Set a default image that will load and then be replaced once the other images load.
$scope.snapshot = 'snapshots/default.png';

Impress.js and AngularJS Controller

I am running an AngularJS application/controller. My goal is to initialize and use the impress.js library on a page that is being dynamically loaded into my main home page. However, when I try to initialize the library, the page does not load. Attached is a snippet of the controller and html file.
NOTE: When I print the impress() object to the console, it is not null, and has the required functions. It is my suspicion that the impress() object is not hooking up to the page correctly.
Controller:
'use strict';
// Create the angular module
var cmodule = angular.module('coverage', ['ngRoute'])
// Create the coverage controller
cmodule.controller('coverageController', function($scope) {
console.log("Entering controller");
function require(script) {
$.ajax({
url: script,
dataType: "script",
async: true, // <-- This is the key
success: function () {
console.log(impress());
impress().init();
},
error: function () {
throw new Error("Could not load script " + script);
}
});
}
console.log("About to require");
angular.element(document).ready(function () {
require("/content/libraries/impress.js");
});
});
HTML File:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=1024" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>My Coverage</title>
<link rel="stylesheet" href="/content/styles/team1.css">
</head>
<body class="impress-not-supported">
<!--
For example this fallback message is only visible when there is `impress-not-supported` class on body.
-->
<div class="fallback-message">
<p>Your browser <b>doesn't support the features required</b> by impress.js, so you are presented with a simplified version of this presentation.</p>
<p>For the best experience please use the latest <b>Chrome</b>, <b>Safari</b> or <b>Firefox</b> browser.</p>
</div>
<!-- Now the fun begins -->
<div id="impress">
<!-- The background image -->
<div class="present" data-x="0" data-y="0">
<!-- Place Image here -->
</div>
<!-- Example content -->
<div id="url-ident" class="step" data-x="0" data-y="0">
<q>Ready to view your coverage?</q>
</div>
<!-- Example content -->
<div id="step1" class="step" data-x="500" data-y="0">
<p>Questions start here!</p>
</div>
</div> <!-- /div impress -->
<script type="text/javascript" src="/content/libraries/impress.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<!--script type="text/javascript">impress().init();</script-->
</body>
</html>
This problem was fixed by using the jmpress.js library instead, found here.

Categories

Resources