So I've tried to make a script which would load the files needed for my AngularJS application.
But when I run the Angular.bootstrap part I get this error
Error description at AngularJS home page
This error is due to AngularJS not being able to find my masterController why is this. I've checked that the name of the module match, as well as the name of the controller and they do. So I'm very confused as to why I won't recognize the controller.
My code looks like this:
Index.html
<!doctype html>
<html ng-controller="masterController">
<head>
<!-- META -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport -->
<meta name="author" content="Michael Tot Korsgaard">
<title>Mythodea map explorer</title>
<link rel="icon" type="image/png" href="favicon.png">
<script src="lib/JQuery/1.12.3/jquery.min.js"></script>
<script src="lib/AngularJS/1.5.5/angular.min.js"></script>
<script src="lib/AngularJS/1.5.5/angular-animate.min.js"></script>
<script src="lib/AngularJS/1.5.5/angular-aria.min.js"></script>
<script src="lib/UI-Router/0.2.18/ui-router.min.js"></script>
<script src="lib/moment/2.13.0/moment.js"></script>
<script src="js/log.js"></script>
<script src="js/build.js"></script>
</head>
<body ng-cloak>
<div ui-view></div>
</body>
</html>
core.js
var app = angular.module('AcademiaUnitate', [
'ui.router',
'ngAnimate'
]);
master.controller.js
angular.module('AcademiaUnitate')
.controller('masterController', function ($scope) {
});
build.js where my angular files are being added to my <head> tag
var buildStart = moment(),
fileCounter = 0;
initialize();
function initialize(){
loadJson('app')
.done(function(response){
var files = response.files,
folders = response.folders;
getFiles(files, 'app')
.done(function(response){
getFolders(folders, 'app')
.done(function(response){
bootstrap();
});
})
});
}
function getFolders(folders, path){
var deferred = $.Deferred();
if(folders.length > 0){
loadFolder(path + '/' + folders[0])
.done(function(response){
folders.splice(0, 1);
getFolders(folders, path)
.done(function(response){
deferred.resolve(response);
});
});
} else {
deferred.resolve(true);
}
return deferred.promise();
}
function getFiles(files, path){
var deferred = $.Deferred();
if(files.length > 0){
loadFile(path + '/' + files[0])
.done(function(response){
files.splice(0, 1);
getFiles(files, path)
.done(function(response){
deferred.resolve(response);
});
});
} else {
deferred.resolve(true);
}
return deferred.promise();
}
function loadFile(src){
var defer = $.Deferred(),
fileType = src.substring(src.lastIndexOf(".") + 1, src.length);
var head = $('head');
fileCounter++;
if(fileType.toLowerCase() === 'js'){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
document.getElementsByTagName('head')[0].appendChild(script);
defer.resolve(true);
} else {
defer.resolve(true);
}
return defer.promise();
}
function loadFolder(path){
var defer = $.Deferred();
loadJson(path)
.done(function(response){
var folders = response.folders,
files = response.files;
if(folders !== undefined){
getFolders(folders, path)
.done(function(response){
if(files !== undefined){
getFiles(files, path)
.done(function(response){
defer.resolve(response);
});
} else {
defer.resolve(response);
}
});
} else {
if(files !== undefined){
getFiles(files, path)
.done(function(response){
defer.resolve(response);
});
} else {
defer.resolve(response);
}
}
});
return defer.promise();
}
function loadJson(path){
var defer = $.Deferred();
$.get(path + '/structure.json', function(response) {
defer.resolve(response);
});
return defer.promise();
}
function bootstrap(){
$(document).ready(function(){
var bootstrapStart = moment();
angular.bootstrap(function(){
});
});
}
What my build.js file does is to find the file structure.json which tells which js files to add to the <head> tag and then which folders to look for additional structure.json files. When all that is done angular will be bootstrapped.
The file containing the masterController function is missing when Angular is bootstraping the application. Include the file. Help this help
You should probably consider naming your controller properly
angular.module('AcademiaUnitate')
.controller('MasterController', function MasterController($scope) {
});
Please see the controller documentation for the latest angular1 version at https://docs.angularjs.org/guide/controller and an example at https://docs.angularjs.org/tutorial/step_02
If all your angular code is in one file, you may want to do the following:
1) chain the controller after/ to the angular.module()
angular.module('AcademiaUnitate', [
'ui.router',
'ngAnimate'
]).controller('MasterController', function MasterController($scope) {
});
OR 2)use the app variable
var app = angular.module('AcademiaUnitate', [
'ui.router',
'ngAnimate'
]);
app.controller('MasterController', function MasterController($scope) {
});
You haven't included core.js in your index.html. That is why your controller is not found. Try including it.
<script src="core.js"></script>
you probably forget to add ng-app="AcademiaUnitate", just change <html ng-controller="masterController"> to <html ng-app="AcademiaUnitate" ng-controller="masterController">
I found the problem, it was the way I bootstrapped my application had to change
angular.bootstrap(function(){});
into
angular.bootstrap(document, ['AcademiaUnitate']);
Related
Json fetching has worked before in site for example here where i used the same processes - https://n-ce.github.io/Sea-arch
Here's the script
//FETCH
function content(a){
fetch(a+'.json').then(function (response) {
return response.json();
}).then(function (data) {
appendData(data);
}).catch(function (err) {
console.log('error: ' + err);
});
}
//Loading the objects
var root = document.getElementById('root');
function appendData(data) {
for (var i = 0; i < data.length; i++) {
var p = document.createElement("p");
p.innerHTML = data[i].Name;
root.appendChild(p);
}
}
// Remove Function
function remove(){
while (root.hasChildNodes()) {
root.removeChild(root.firstChild);
}
}
// Click decision making
var count = couns = 0;
function Sites() {
if(count%2==0){
content('Sites');
count++;
}
else{
count--;
remove();
}
}
function Animals() {
if (couns % 2 == 0) {
content('Animals');
couns++;
}
else {
couns--;
remove();
}
}
And this is the HTML
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON SD</title>
<link rel="stylesheet" href="style.css"/>
</head>
<body onload="content('Onload')">
<span>
<button onclick="Animals()">Load Animals</button>
<button onclick="Sites()">Load Sites</button>
</span>
<div id="root"></div>
<script src="script.js"></script>
</body>
</html>
There is no way for me to debug this given that the console doesnot throw any errors since its working fine in localhost.
Im fairly new to the Fetch API But
Im thinking maybe it is because the json files are being transferred are taking too long?
Can someone please highlight whats the issue?
Here's how it worked for github pages, thanks to #programmarRaj for highlighting
Script
//FETCH
function content(a){
fetch("./"+a+".json").then(function (response) {
return response.json();
}).then(function (data) {
appendData(data);
}).catch(function (err) {
console.log('error: ' + err);
});
}
I am running qunit Test using html file in one file and that html file i am running from phantom js.
When I am running html file through browser i am getting output in console but when i am trying to run using phantom js i am not getting the console output in another js file from where i am calling html file.
I am providing both Files:
HTML File :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JUnit reporter for QUnit</title>
<link rel="stylesheet" href="qunit.css">
<script src="qunit.js"></script>
<script>
QUnit.config.reorder = false;
</script>
<script src="qunit-reporter-junit.js"></script>
<script src=" http://requirejs.org/docs/release/2.2.0/minified/require.js"></script>
<script>
QUnit.jUnitDone(function(data) {
var console = window.console;
if (console) {
console.log(data.xml);
}
});
</script>
<script src="qunit-reporter-junit.test.js"></script>
</head>
<body>
<div id="qunit"></div>
</body>
</html>
Js file :
var system = require('system');
var fs = require('fs');
var page = require('webpage').create();
if (system.args.length === 1) {
console.log('Pass the path/to/testfile.js as argument to run the test.');
phantom.exit();
} else {
var url = "file:///C:/Users/Admin/Desktop/js/index.html"; // e.g. 'test/unit/tests.html'
console.log("Opening " + url);
}
page.open(url, function (status) {
console.log("Status: " + status);
if (status === "success") {
setTimeout(function () {
var path = 'results.xml';
var output = page.evaluate(function () {
// wants to take console output from html page
.....................................?
});
fs.write(path, output, 'w');
console.log("Wrote JUnit style output of QUnit tests into " + path);
console.log("Tests finished. Exiting.");
phantom.exit();
}, 3000);
} else {
console.log("Failure opening" + url + ". Exiting.");
phantom.exit();
}
});
can anyone suggest me how to take the console output from html file ?
Thanks In Advance.
If your test is similar to this example then to get test results you should request the contents of #qunit-testresult element.
var output = page.evaluate(function(){
return document.getElementById("qunit-testresult").innerText
});
This is my html file:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="Content-Script-Type" content="text/javascript"/>
</head>
<body>
<label for=payload>Payload</label><br>
<textarea id="editor" cols=100 rows=30></textarea><br>
</body>
And the phantomjs script is:
var bodyParser = require('body-parser'),
phantom = require('phantom');
var bk = {"abc":"def"};
//Create Phantom session
var _phSession;
var _page;
var log = console.log;
var config = { logger: { warn:log, info:log, error:log } };
phantom.create([], config).then(function(_session) {
if (_session) {
console.log('Phantom session created');
_phSession = _session;
return _phSession.createPage();
}
})
.then(function(page) {
_page = page;
_page.property('onConsoleMessage', function(msg) {
console.log(msg);
});
_page.property('onLoadStarted', function() {
console.log("load started");
});
_page.property('onLoadFinished', function() {
console.log("load finished");
});
return _page.open("http://myserver/my.html");
})
.then(function(status) {
console.log('Open status:' + status);
if (status != 'success') return;
_page.includeJs('https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js')
.then(function() {
//set the new bkstore
_page.evaluate(function(bk) {
jQuery('#editor').val(JSON.stringify(bk));
return jQuery('#editor').val();
}, bkstore)
.then(function(res) {
console.log('Return from set:' + res);
})
});
setTimeout(function() {
_page.evaluate(function() {
console.log('============== EVALUATE AFTER LOADED ===================');
//return jQuery('#editor').val();
return jQuery('body').html();
})
.then(function(res) {
console.log('html:' + res);
});
}, 1000);
After I set the #editor content with bk, I get back the value I set.
In the block of setTimeout, if I try to get the content of #editor again, I still get back the value of bk.
But I get the html of the body tag, I don't see the value of bk in the #editor.
Anyone knows what the problem is?
I am trying to load some javascript dynamically using AngularJS promises.
HTML file (index.html)
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular-route.js"></script>
<script type="text/javascript" src="main.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body ng-app="main">
<ng-view></ng-view>
</body>
</html>
AngularJS file (main.js)
angular.module('main', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/',
{
controller: 'MainCtrl',
templateUrl: 'partial.html',
resolve: {
temp: MainCtrl.testFn
}
})
.otherwise({
redirectTo: '/'
})
})
MainCtrl = angular.module('main')
.controller('MainCtrl', function () {
});
angular.module('main')
.factory('MyFactory', function($q) {
data = {
loadJS: function() {
var deferred = $q.defer()
var script = document.createElement('script');
script.type = 'text/javascript'
script.src = 'https://apis.google.com/js/client.js'
script.onload = function() {
deferred.resolve('Google Client Library loaded')
}
document.body.appendChild(script)
return deferred.promise
}
}
return data
})
MainCtrl.testFn = function($log, MyFactory) {
return MyFactory.loadJS().then(function(result) {
$log.debug(result)
gapi.client.load()
})
}
The onload method is called (as the promise is resolved and debug line printed), but an error is being thrown because the client property is not found on gapi (Uncaught TypeError: Cannot read property 'load' of undefined).
What am I missing? Does anyone have a better way of dynamically loading JS with Angular promises (using only Angular and JS)?
I guess, the script is loading successfully but gapi.client is not available immediately. You need to provide handler to google api url on that purpose (some global function).
angular.module('app', [])
.controller('mainCtrl', function(googleClientLoader) {
googleClientLoader.load().then(
function() {
console.debug(gapi.client);
}
)
})
.factory('googleClientLoader', function($q) {
return {
load: function() {
var deferred = $q.defer()
var script = document.createElement('script');
script.type = 'text/javascript'
script.src = 'https://apis.google.com/js/client.js?onload=handleClientLoad';
window.handleClientLoad = function() {
deferred.resolve('Google Client Library loaded');
}
document.body.appendChild(script)
return deferred.promise;
}
}
})
Just load the content and use eval(data) to evaluate the Javascript.
a tag won't be processed as it is generated after the page loads.
Why am I getting this error, when I'm trying to get a response from a file on my own server?
$.get("http://www.example.com/user.php?q=" + client + "", function(response) {
if(response == "invalid"){
console.log("invalid login");
return;
}
And btw, the string client is mentioned already in the code.
And jquery is included.
http://i.gyazo.com/693e6633d211ab6da79598e75c6dde58.png
I have solve the problem like this ( i have jquery loaded async so i check if is defined and then get a css...etc..)
<script id="jquery" type='text/javascript' async defer src='//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js?ver=1.8.3'></script>
<script type='text/javascript'>
(function checkJQuery(){
if ('undefined' == typeof window.jQuery) {
setTimeout(function(){checkJQuery();},250);
}else{
var css = "url-of-my-css";
console.log("my css is loading");
window.jQuery.get( css, function( data ) {
$('<style>'+ data +'</style>').appendTo(document.getElementsByTagName('head')[0]);
console.log("css loaded");
});
var js = document.createElement('script');
js.type = 'text/javascript';
js.async = 'async';
js.defer = 'defer';
js.src = 'url-of-my-js';
var node = document.getElementsByTagName('script')[1];
node.parentNode.insertBefore(js, node);
}
})();
</script>
Changing $.get to window.JQuery.get
Hope this help.
I had a problem like this in asp.net mvc 5.
<script>
function OpenBulkUpload() {
$.get("/AdminPanel/BulkUpload/Index").then(
function (r) {
$("<div id='DivBulkUpload'></div>").html(r).dialog(
{
width: 'auto', height: 'auto', modal: true, title: "Upload Pictures",
close: function () { $('#DivBulkUpload').remove(); }});
});
}
</script>
show Uncaught TypeError: Cannot read property 'get' of undefined in debuger browser.
solution:
1.By adding jquery UI in package manager console
PM> install-package Jquery.UI.combined
2.And add scripts and links in top of cshtml page
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-ui-1.11.4.js"></script>
<link href="~/Content/themes/base/all.css" rel="stylesheet" />
My problem was solved.
I think this will work:
$.get("http://www.example.com/user.php?q=" + client, function(response) {
if(response == "invalid"){
console.log("invalid login");
return;
}
});