Best way to load/store ndDialog template? - html

I am using ngDialog to display a modal window with an alert message.
I have the modal window working however the code looks messy.
I am wondering is it possible to replace the raw html template with a link to a html file instead of writing the HTML within the function itself.
$scope.openDialog = function(components) {
$scope.selected = components.component;
ngDialog.open({
template: '<h4>' + 'Alert' + '</h4>' +
'<table class="table">' +
'<tr><th>Type</th><td>' + components.type + '</td></tr>' +
'<tr><th>Component</th><td>' + components.component + '</td></tr>' +
'<tr><th>Created</th><td>' + components.created + '</td></tr>' +
'<tr><th>Alert</th><td>' + components.alert + '</td></tr>'+
'</table>',
plain: true
});
};

Yep, just use templateUrl rather than template.
$scope.openDialog = function(components) {
$scope.selected = components.component;
ngDialog.open({
templateUrl: 'yourfilename.html',
plain: true
});
};

Related

How to use POST in ajax

I created a page where after loading the data will appear. I am using github url and ajax POST. But the data is not showing. What should I fix from the code that I have made?
<div id="content">
</div>
window.onload = function(){
$.ajax({
type: 'POST',
url: 'https://raw.githubusercontent.com/bimobaskoro/hewan/main/kucing.json',
dataType: 'application/json',
sucess: function (data) {
html = '<div class="content" id="content"></div>'
html += '<h1>' + data.judul + '</h1>'
html += '<p>' + data.isi + '</p>'
html += '</div>'
document.getElementById('content').innerHTML += html;
},
error: function() {
}
});
}
Consider the following.
$(function(){
$.getJSON("https://raw.githubusercontent.com/bimobaskoro/hewan/main/kucing.json", function (data) {
var html = $("<div>", {
class: "content"
});
$("<h1>").html(data.judul).appendTo(html);
$("<p>").html(data.isi).appendTo(html);
$("#content").append(html);
});
}
As GitHub is not apart of the same domain, you may encounter CORS issues. If so, you might consider JSONP.
Why would you use post to a json file. Get method is enough.
$.ajax({
url: 'https://raw.githubusercontent.com/bimobaskoro/hewan/main/kucing.json',
success: function (data)
{
var html = '<div class="content" id="content">';
var obj=JSON.parse(data);
obj.forEach((e)=>{
html += '<h1>' + e.judul + '</h1>'
html += '<p>' + e.isi + '</p>'
});
html += '</div>'
document.getElementById('content').innerHTML = html;
}
});

HTML Table data will disappear after page refresh

I am using a web service to get data from MySQL database and show them in a HTML Table. And it is working data will appear in the table. But when I reload the page Table data will disappear. How can I fix that? How can I keep data even page reloaded?
HTML
<body>
<button id="btnSearch">Search</button>
<table id="tab">
</table>
</body>
And the following JS.
<script type="text/javascript">
$("#btnSearch").click(function()
{
$.getJSON("http://localhost:8080/Service/Rest/cart/get/cart",function(data)
{
var tb = $("#tab");
$.each(data,function(i,value)
{
tb.append("<tr><td>Product Name: " + value.name + "</td><td>Price: " + value.price + " </td><td>Description: " + value.description + "</td></tr>");
});
});
});
</script>
<script type="text/javascript">
$( document ).ready(function() {
$.getJSON("http://localhost:8080/Service/Rest/cart/get/cart",function(data)
{
var tb = $("#tab");
$.each(data,function(i,value)
{
tb.append("<tr><td>Product Name: " + value.name + "</td><td>Price: " + value.price + " </td><td>Description: " + value.description + "</td></tr>");
});
});
});
$("#btnSearch").click(function()
{
$.getJSON("http://localhost:8080/Service/Rest/cart/get/cart",function(data)
{
var tb = $("#tab");
$.each(data,function(i,value)
{
tb.append("<tr><td>Product Name: " + value.name + "</td><td>Price: " + value.price + " </td><td>Description: " + value.description + "</td></tr>");
});
});
});
</script>
I have another solution for this, create a dummy table data with null value, and store your value in browser session and then replace all the null value on runtime through jquery/javascript.
Hope this helps.

How to test a directive with a scroll event?

I'm trying to test a directive that allows me to do infinite scroll in my app. The directive works fine in my production code.
This question is really close to How to test AngularJS Directive with scrolling and if someone says they are identical questions, I'll delete this one. However, it is not solving my problem (at least I cannot figure out how).
Here's my directive:
(function(){
"use strict";
angular.module('moduleA').directive('whenScrolled',Directive);
Directive.$inject = [];
function Directive(){
return {
restrict : 'A', // Restrict to Attributes
link : postLink
};
// Bind the element's scroll event
function postLink(scope,elem,attr){
var raw = elem[0];
elem.bind('scroll',eventMethod);
function eventMethod(){
if ( raw.scrollTop + raw.offsetHeight >= raw.scrollHeight ) {
scope.$apply(attr.whenScrolled);
}
};
};
};
})();
And here's my Karma test:
describe('whenScrolled Directive:',function(){
beforeEach(module('moduleA'));
// Create a list in HTML and force overflow for a scroll event
var html =
'<div id="test" ' +
' style="max-height:30px;overflow-y:scroll;" ' +
' when-scrolled="testScroll()">' +
' <ul>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' </ul>' +
'</div>';
var $rootScope,
element;
beforeEach(inject([
'$compile','$rootScope',
function($compile,$rs){
$rootScope = $rs;
$rootScope.isScrolled = false;
$rootScope.testScroll = function(){
$rootScope.isScrolled = true;
};
element = $compile(html)($rootScope);
$rootScope.$digest();
}
]));
it('should activate on scroll',function(){
expect(element).toBeDefined();
$rootScope.$broadcast('scroll'); <-- does nothing? -->
expect($rootScope.isScrolled).toBe(true); <-- fails -->
});
});
My karma.conf.js:
// Created May 04, 2016
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'vendor/angular/angular.js',
'vendor/angular/angular-mocks.js',
'moduleA/moduleA.view.html',
'moduleA/moduleA.module.js',
'moduleA/moduleA.controller.js',
'moduleB/moduleB.view.html',
'moduleB/moduleB.module.js',
'moduleB/moduleB.controller.js',
'test/module-A-tests.js',
'test/module-B-tests.js'
],
// list of files to exclude
exclude: [
'vendor/bootstrap*',
'vendor/jquery*',
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma- preprocessor
preprocessors: {
// karma-ng-html2js-preprocessor for templates in directives
'moduleA/moduleA.form.view.html': 'ng-html2js',
'moduleB/moduleB.view.html': 'ng-html2js'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
My thought was that if I have $rootScope broadcast 'scroll' out to all of it's children (in my case, $scope), and $scope was tied to my element with my directive, then that would trigger the method I provided (doScrollFn), and $scope.isScrolled would change.
But as far as I can tell, the doScrollFn never gets triggered.
I'm still not 100% sure what I did wrong, but after googling karma-ng-html-preprocessor, I found this:
https://www.npmjs.com/package/karma-ng-html2js-preprocessor-with-templates which lead me to:
https://github.com/vojtajina/ng-directive-testing which lead me to:
https://angularjs.org/#create-components and mainly, this:
https://github.com/vojtajina/ng-directive-testing/blob/start/test/tabsSpec.js.
And here's my test that works:
describe('whenScrolled Directive',function(){
beforeEach(module('moduleA'));
var html =
'<div id="test" ' +
' style="min-height:5px;max-height:30px;overflow-y:scroll;" ' +
' when-scrolled="testScroll()">' +
' <ul>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' <li>Testing</li>' +
' </ul>' +
'</div>';
var $rootScope,
element;
beforeEach(function(){
inject([
'$compile','$rootScope',
function($compile,$rs){
$rootScope = $rs;
$rootScope.isScrolled = false;
$rootScope.testScroll = function(){
$rootScope.isScrolled = true;
};
element = angular.element(html);
$compile(element)($rootScope);
$rootScope.$digest();
}
]);
});
it('should activate on scroll',function(){
expect(element.find('li').length).toBe(10);
element.triggerHandler('scroll');
expect($rootScope.isScrolled).toBe(true);
});
});
If this saves anybody some time and trouble, then it was worth the write-up.

Phonegap - HTML does not display image from storage

I'm using FileTransfer plugin to download an image from a remote server.
The image is stored in "storage/emulated/0/" - using the following code:
function downloadFile(fileDownloadName){
//console.log('downloadFile');
window.requestFileSystem(
LocalFileSystem.PERSISTENT,
0,
function(fileSystem){
//console.log('onRequestFileSystemSuccess');
fileSystem.root.getFile(
'dummy.html',
{create: true, exclusive: false},
function(fileEntry){
//console.log('onGetFileSuccess!');
var path = fileEntry.toURI().replace('dummy.html', '');
var fileTransfer = new FileTransfer();
fileEntry.remove();
fileTransfer.download(
'https://www.myserver.com/imagens/' + fileDownloadName,
path + fileDownloadName,
function(file) {
//console.log('download complete: ' + file.toURI());
return path + fileDownloadName;
},
function(error) {
console.log('download error source ' + error.source);
console.log('download error target ' + error.target);
console.log('upload error code: ' + error.code);
}
);
},
fail
);
},
fail
);
}
So, I'm pointing the path + fileDownloadName to SRC of my image, but the image does not appear.
var location = path + fileDownloadName;
window.resolveLocalFileSystemURL(location, function(oFile) {
oFile.file(function(readyFile) {
var reader= new FileReader();
reader.onloadend= function(evt) {
$(".circle-perfil").css('background-image', 'url(' + evt.target.result + ')');
};
reader.readAsDataURL(readyFile);
});
Is there something wrong I'm doing? Should I have to store the image in another folder? If yes, how to do it?
If you are using img tag then set its image as:
$(".circle-perfil").css('background', 'url(' + evt.target.result + ')');
or
$(".circle-perfil").css('content', 'url(' + evt.target.result + ')');
In case of div or span
$(".circle-perfil").css('background-image', 'url(' + evt.target.result + ')');
I had set it like:
var image = document.getElementById('cameraPic');
image.src = 'path/of/image file';

How to parse JSON url of api data and display in div

I want to get the data from Json url api page, how can i get this, please help me in this regards
$(document).ready(function() {
$("#driver").click(function(event){
$.getJSON('http://globalmetals.xignite.com/xGlobalMetals.json/GetLondonFixing?Symbol=XAU&Currency=USD', function(data) {
var json = $.parseJSON(data);
$('#stage').html('<p> Outcome: ' + json.Outcome + '</p>');
$('#stage').append('<p>Message : ' + json.Message+ '</p>');
$('#stage').append('<p> Name: ' + json.Name+ '</p>');
});
});
});
When you use $.getJSON, the data is already parsed for you, it's wrong to call $.parseJSON.
$.getJSON('http://globalmetals.xignite.com/xGlobalMetals.json/GetLondonFixing?Symbol=XAU&Currency=USD', function(json) {
$('#stage').html('<p> Outcome: ' + json.Outcome + '</p>');
$('#stage').append('<p>Message : ' + json.Message+ '</p>');
$('#stage').append('<p> Name: ' + json.Name+ '</p>');
});