Hi i have been facing this issue for over a long time. I can able to found at the place,it is due to the ng-app in the html page. However i have the proper food module in js. What could the be the cause of this error? any idea? my code
INDEX.HTML
<!DOCTYPE html>
<html ng-app="food">
<head>
<title>Scratchpad</title>
<!-- Viewport mobile tag for sensible mobile support -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!--
Stylesheets and Preprocessors
==============================
You can always bring in CSS files manually with `<link>` tags, or asynchronously
using a solution like AMD (RequireJS). Or, if you like, you can take advantage
of Sails' conventional asset pipeline (boilerplate Gruntfile).
By default, stylesheets from your `assets/styles` folder are included
here automatically (between STYLES and STYLES END). Both CSS (.css) and LESS (.less)
are supported. In production, your styles will be minified and concatenated into
a single file.
To customize any part of the built-in behavior, just edit `tasks/pipeline.js`.
For example, here are a few things you could do:
+ Change the order of your CSS files
+ Import stylesheets from other directories
+ Use a different or additional preprocessor, like SASS, SCSS or Stylus
-->
<!--Twitter Bootstrap-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<!--STYLES-->
<link rel="stylesheet" href="/styles/importer.css">
<!--STYLES END-->
</head>
<body>
<nav class = "navbar navbar-default" role = "navigation">
<div class = "container-fluid">
<div class = "navbar-header">
<a class = "navbar-brand" ui-sref = "scratchpad">FoodForShare</a>
</div>
</div>
</nav>
<p>SAMPLE PAGE</p>
<div class = "container">
<div ui-view></div>
</div>
<!--
Client-side Javascript
========================
You can always bring in JS files manually with `script` tags, or asynchronously
on the client using a solution like AMD (RequireJS). Or, if you like, you can
take advantage of Sails' conventional asset pipeline (boilerplate Gruntfile).
By default, files in your `assets/js` folder are included here
automatically (between SCRIPTS and SCRIPTS END). Both JavaScript (.js) and
CoffeeScript (.coffee) are supported. In production, your scripts will be minified
and concatenated into a single file.
To customize any part of the built-in behavior, just edit `tasks/pipeline.js`.
For example, here are a few things you could do:
+ Change the order of your scripts
+ Import scripts from other directories
+ Use a different preprocessor, like TypeScript
-->
<script src="/js/dependencies/sails.io.js"></script>
<script src="/js/bower_components/angular/angular.min.js"></script>
<script src="/js/bower_components/angular-route/angular-route.min.js"></script>
<script src="/js/bower_components/jquery/dist/jquery.min.js"></script>
<script src="/js/bower_components/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/main.js"></script>
<script src="/js/routes.js"></script>
<script src="/js/service/crud.js"></script>
</body>
</html>
MAIN.JS
/**
* Defines module-scratchpadModule for the application
*#dependencies: ui-router , Angular - resource
*#states: 2 Parent states and 1 Child state
*#Controllers: Controllers for listing, viewing and adding a scratch
*#Factory Service: Notes for the angular resource
*
*
*
*
*/
var foodshareModule= angular.module('food',['ngRoute','ngResource']);
console.log("Main file getting included");
foodshareModule.controller("personController", function($scope) {
console.log($scope);
$scope.firstName = "John";
$scope.lastName = "Doe";
console.log($scope.firstName);
console.log($scope.lastName);
});
foodshareModule.controller('scratchListController', function($scope,$state,Notes){
console.log("working");
$scope.scratchpad =Food.query();
$scope.deleteScratch = function (scratch,flag) {
if(flag === 0) { //Checks if Bulk delete or single delete
if(confirm("You Clicked DELETE !! Are you sure ?")) {
scratch.$delete(function() { //Single delete
window.location.href = 'http://localhost:1337';
});
}
}
else { //Bulk delete
scratch.$delete(function() {
window.location.href = 'http://localhost:1337';
});
}
}
$scope.emptyScratchpad = function () {
var ask = false;
if (confirm ("You are about Empty Scratchpad. Sure ????")) {
ask = true;
}
if(ask === true) {
for (var i = 0; i < $scope.scratchpad.length; i++) {
$scope.deleteScratch($scope.scratchpad[i],1);
}
}
}
})
foodshareModule.factory('Food', function($resource) {
return $resource('http://localhost:1337/Food:id', { id: '#_id' }, {
update: {
method: 'PUT'
}
});
});
ERROR:
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.15/$injector/modulerr?p0=food&p1=TypeError%…calhost%3A1337%2Fjs%2Fbower_components%2Fangular%2Fangular.min.js%3A17%3A1)
you have not included ngResource script file. ngResource doesnt come pre bundled with angular.js
<script src="path-to-js/angular-resource.min.js"></script>
Related
I am currently learning about objects within class. I created an object with constructor notation in Javascript, and instantiated four different objects with distinct names. For some reason, when I try to run the Captain.speak() method in my code, it doesn't work. It should display the Captain.strPhase string that I created right before initiating the command for the function. When I check this in online compilers, there are no errors, but it doesn't output my string. Would anyone happen to know why?
$(document).ready(function() {
function Pirate(rank, phrase, id) {
output = "";
randNum = 1;
secretNum = 1;
this.strRank = rank;
this.intNum = favnum;
this.strPhrase = phrase;
this.elOutput = document.getElementById(id);
this.speak = function() {
this.elOutput.innerHTML += "<br>" + this.strPhrase;
}; //End speak
this.chooseRandNum = function() {
this.randNum = Math.floor(Math.random() * 10);
}; //End chooseRandNum
}; //End Pirate
var Captain = new Pirate("Captain", "", "captain");
var firstMate = new Pirate("First Mate", "I love guessing games!", "pirate1");
var Quartermaster = new Pirate("Quartermaster", "This game should be fun.", "pirate2");
var Gunner = new Pirate("Gunner", "Let's start playing!", "pirate3");
Captain.strPhrase = "Argh maties, ready to play a guessing game?";
Captain.speak();
}); // end of $(document).ready()
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Begin every html page with everything up to this point (just use your own header block) -->
<!-- Also, feel free to remove all the instructional comments as you modify this file to make it yours. -->
<!-- This <title> displays in the page tab -->
<title>Randomness</title>
<!-- This will link to your CSS stylesheet for formatting as soon as you create the file. The page will work without it, though. -->
<link rel="stylesheet" href="css/myFancyStylesheet.css">
<!-- This links to the jQuery library so your js code will work
Always include this *before* your own js code (extremely important) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This links to the js code specific for this page -->
<script src="Randomness.js"></script>
</head>
<body>
Captain's Guessing Game:
<br></br>
<div id="captain">
</div>
<br></br>
<div id="pirate1">
</div>
<br></br>
<div id="pirate2">
</div>
<br></br>
<div id="pirate3">
</div>
</body>
</html>
When I run your code, I get an error message:
Uncaught ReferenceError: favnum is not defined
If you comment out this line...
// this.intNum = favnum;
...everything should work just fine.
My code works fine when I add my module straight into the html code, but it won't load it when I try to first import the module to a different javascript file.
I've tried exporting everything, from my module.
HTML:
<html>
<head>
<title>
Hello world
</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Tradingpost, done by no css gang.</h1>
<div id="sidenav">Here be the links to other pages</div>
<br>
<footer id="footer">
Done whenever. Copyright is mine.
</footer>
<script src="js/app.js"></script>
</body>
</html>
app.js:
import * as sidebar from "./visualModules/sidebarmodule"
function cumulator() {
sidebar.createSidebar()
}
sidebarmodule.js:
function sidebarAdder(pages) {
const sidebar = document.getElementById("sidenav")
const list = document.createElement("UL")
for(index = 0; index < pages.length; index++) {
const ul = document.createElement("LI")
const a = document.createElement("A")
a.setAttribute("href", "/" + pages[index])
a.innerHTML = "" + pages[index]
ul.appendChild(a)
list.appendChild(ul)
}
sidebar.appendChild(list)
}
export function createSidebar() {
var pages = [
"home",
"tradingpost"
]
sidebarAdder(pages)
}
It should add elements to the div. But it wont do it unless I straight up use the sidebarmodule.js. I want to do it through the app.js
EDIT
Found the problem!
Didn't initialize index in the for loop.
EDIT2
And the type="module" which needed to be added
When you load your app.js in your html file, try to add:
<script type="module" src="js/app.js"></script>
That should work when you want to use ESModules. But please update us regardless :)
Update:
Ok after creating a project myself using your HTML and JS, I found a few errors.
First: When using ESModules, you can't use any functions in the JS through your HTML, you will have to inject everything from the app.js.
index.html:
<body>
<div id="sidenav">
Here be the links to other pages
</div>
<br>
<footer id="footer">
Done whenever. Copyright is mine.
</footer>
<script type="module" src="js/app.js"></script>
app.js:
import { createSidebar } from './visualModules/sidebarmodule.js';
cumulator();
function cumulator() {
createSidebar()
}
Notice two things: at the end of the import, since we are not using a compiler, the modules do not recognize files without their extension. So I had to add .js to sidebarmodule. Secondly, I had to invoke cumulator function within the app.js file (like I said earlier, you cannot use any module functions outside their scope. There are no global variables with ESModules).
sidebarmodule.js:
function sidebarAdder(pages) {
const sidebar = document.getElementById("sidenav")
const list = document.createElement("UL")
for(var index = 0; index < pages.length; index++) {
const ul = document.createElement("LI")
const a = document.createElement("A")
a.setAttribute("href", "/" + pages[index])
a.innerHTML = "" + pages[index]
ul.appendChild(a)
list.appendChild(ul)
}
sidebar.appendChild(list)
}
export function createSidebar() {
var pages = [
"home",
"tradingpost"
]
sidebarAdder(pages)
}
You did not declare index inside your for loop, so I just added a var.
Hope this helps.
import is asynchronous in Javascript (in a browser, not Node.js) so you're calling createSidebar() before the module is loaded. You can use import to return a promise so you can execute code once it is completed.
Remove the embedded Javascript from your html, but leave the link to app.js. Then change app.js to this...
import("./visualModules/sidebarmodule")
.then((sidebar) => {
sidebar.createSidebar();
});
Sorry for the bad english :P
I'm using ASP.NET
I'm trying to use a JavaScript that I've found on the Internet to set masks to my telephone and cellphone text fields, but the JS code just work at the fields that are located at my MasterPage. I don't have much experience with JS (almost none) and I have no idea how to resolve this since there is no error at my Logcat.
I tried to reference it at my MasterPage's head, body and inside the ContentPlaceHolder.
Here is the JS code:
function mascara(o, f) {
v_obj = o
v_fun = f
setTimeout("execmascara()", 1)
}
function execmascara() {
v_obj.value = v_fun(v_obj.value)
}
function mtel(v) {
v = v.replace(/\D/g, "");
v = v.replace(/^(\d{2})(\d)/g, "($1)$2");
v = v.replace(/(\d)(\d{4})$/, "$1-$2");
return v;
}
function id(el) {
return document.getElementById(el);
}
window.onload = function () {
id('txtTelefone').onkeypress = function () { //Located at MasterPage - working
mascara(this, mtel);
}
id('txtCelular').onkeypress = function () { //Located at MasterPage - working
mascara(this, mtel);
}
id('telefoneContato').onkeypress = function () { //Located at Contact Page - not working
mascara(this, mtel);
}
id('txtCelularUser').onkeypress = function () { //Located at User Page - not working
mascara(this, mtel);
}
id('txtTelefoneUser').onkeypress = function () { //Located at User Page - not working
mascara(this, mtel);
}
}
As I said before I tried to reference my JS file in some places, the codes that I tried were:
<script src="<%# Page.ResolveClientUrl("../Componentes/js/mascaras.js") %>"></script>
<script src="../Componentes/js/mascaras.js"></script>
As you can see, the fields are located in diferent pages, I also tried to put the code directly at the pages but I had no luck.
I think that I don't need to post my entire MasterPage here, then I'll put just the head, but if exists a need I will edit the post.
<head runat="server">
<title></title>
<link rel="shortcut icon" href="../imagens/icone.ico" type="image/x-icon" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="utf-8" />
<link href="../Componentes/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen" />
<link href="../Componentes/fontawesome/css/font-awesome.min.css" rel="stylesheet" media="screen" />
<link href="../Componentes/css/MasterPage.css" rel="stylesheet" />
<link href="../Fontes/Fontes.css" rel="stylesheet" />
<script src="../Componentes/bootstrap/js/jquery-1.12.4.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/ScrollMagic.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/plugins/debug.addIndicators.min.js"></script>
<script src="../Componentes/bootstrap/js/bootstrap.min.js"></script>
<%--Mask Scripts--%>
<script src="<%# Page.ResolveClientUrl("../Componentes/js/mascaras.js") %>"></script>
<script src="../Componentes/js/mascaras.js"></script>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
EDIT 1
Tried this:
id('<%= txtTelefoneContato.ClientID %>').onkeypress = function () { //Located at Contact Page - Still not working
mascara(this, mtel);
}
id('<%= txtCelularUser.ClientID %>').onkeypress = function () { //Located at User Page - Still not working
mascara(this, mtel);
}
id('<%= txtTelefoneUser.ClientID %>').onkeypress = function () { //Located at User Page- Still not working
mascara(this, mtel);
}
The reference to the script is at MasterPage head. But the problem still the same
EDIT2
Im receiving this when I inspect my page:
Error image 1
Error image 2
Resolved
As VDWWD explained, I just put the JS code directly at the .aspx pages with this modification:
from:,
id('txtCelularUser').onkeypress = function () {
mascara(this, mtel);
}
to:
id('<%= txtCelularUser.ClientID %>').onkeypress = function () {
mascara(this, mtel);
}
Thank you in advance
You have to use it like this when accessing elements with JavaScript that have master pages. And it's also better to use it even without master pages. If you should change the ID in you don't have to change it also in your script.
id('<%= txtTelefoneUser.ClientID %>').onkeypress
If you look at the HTML source you will see that the ID of the element has been changed from txtTelefoneUser to something like this ContentPlaceHolder_txtTelefoneUser. Aspnet adds a prefix to ensure every element has a unique ID.
You will see the same usage of prefix in elements that repeat data like GridView/Repeater/DataList etc.
UPDATE
If you put the javascript in an external file you can put a reference to it on the master page like this (assuming Componentes is a folder in the root):
<script src="/Componentes/js/mascaras.js" type="text/javascript"></script>
However putting <%= txtTelefoneUser.ClientID %> in an external file will not work, only on an .aspx page. To make that work declare those elements as variables an assign them on the aspx page while using them in the external js file.
Below a demo:
In the external javascript file:
var myElement;
function myFunction() {
myElement.value = "Success!";
}
and then on the .aspx page:
<script type="text/javascript">
myElement = document.getElementById("<%= TextBox1.ClientID %>");
</script>
After a long time I found that the elements that area inside the Content to be found in javascript must have the name of the content ID in front more undeline and the name of the element ID, you are looking for.
example:
document.querySelector("#ContentPlaceHolder1_img1").setAttribute("src", 123);
I am creating an O365 app and I have 2 .aspx files, when the user clicks on the O365 mail app, I want each of these pages to be loaded based on the subject of the mail.
Scenario 1: Mail subject contains '#'
result: load page1
Scenario 2: Mail subject does not contain '#'
result: load page2
I have tried having an intermediate .js file where I have written the logic,
but when I do window.location = "path_to_aspx_file",
only the html is loaded but the js files do not run.
My current implementation:
I have LandingLogic.js
(function () {
"use strict";
//The Office initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
var item = Office.cast.item.toItemRead(Office.context.mailbox.item);
var sub = item.subject;
if (sub.indexOf("some text") > -1) {
window.location = "http://localhost:51776/File1.aspx";
}
else {
window.location = "http://localhost:51776/File2.aspx";
}
});
};
})();
After a bit of fumbling around.
I am able to navigate to each of these files now, but I am not sure how to access the mail subject from File1.aspx and File2.aspx.
Did you initialize the Office context before you using Office JavaScript API to get the subject? To redirect the HTML page easily, we can include the JavaScript like below:
Home.js:
/// <reference path="../App.js" />
(function () {
"use strict";
// The Office initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
app.initialize();
RedirectHTMLPage();
});
};
function RedirectHTMLPage() {
var subject = Office.context.mailbox.item.subject;
if (subject.indexOf("#") != -1) {
window.location.href = "https://localhost:44300/page1.aspx";
} else {
window.location.href = "https://localhost:44300/page2.aspx";
}
}
})();
The HTML page for redirecting:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<title></title>
<script src="../../Scripts/jquery-1.9.1.js" type="text/javascript"></script>
<link href="../../Content/Office.css" rel="stylesheet" type="text/css" />
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js" type="text/javascript"></script>
<!-- To enable offline debugging using a local reference to Office.js, use: -->
<!-- <script src="../../Scripts/Office/MicrosoftAjax.js" type="text/javascript"></script> -->
<!-- <script src="../../Scripts/Office/1/office.js" type="text/javascript"></script> -->
<link href="../App.css" rel="stylesheet" type="text/css" />
<script src="../App.js" type="text/javascript"></script>
<link href="Home.css" rel="stylesheet" type="text/css" />
<script src="Home.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>
I have tried having an intermediate .js file where I have written the logic, but when I do window.load = "path_to_aspx_file", only the html is loaded but the js files do not run.
Would you mind sharing the detail you using the “window.load”?
Fei Xue answer is correct . if you want to get subject from file2.aspx , add office.js reference and access subject same as file1.aspx inside the Office.initialize event
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js" type="text/javascript"></script>
I'm building a small application in Play and have an 'outer' template which holds all my CSS and JS imports (jQuery and my main.js file). CSS at the top, JS at the bottom with a body tag in between... pretty basic stuff:
<html>
<head>
<title>test</title>
<link rel="stylesheet" href="#routes.Assets.at("stylesheets/foundation.css")">
<link rel="stylesheet" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
</head>
<body>
#content
</body>
<script src='#routes.Assets.at("javascripts/jquery-1.9.0.min.js")' type="text/javascript"></script>
<script src='#routes.Assets.at("javascripts/index.js")' type="text/javascript"> </script>
</html>
Which is fine.
However, I have page specific javascript functions that should run based on what the page is. So if I go to localhost:9000/test, I want a particular set of functions to run.
If I go to localhost:9000/chips, I want another set of functions to run.
I can't see a neat way of doing this, really, except checking the current page url in the script and executing functions based on that... but the routes file is already doing stuff based on the current page url - seems strange to have to do something so similar twice.
One solution is to put all my scripts at the top and then execute inline scripts in the HTML... but I hate doing things like that.
You have very nice and clear sample available in the... documentation.
Scroll to the bottom and check section: moreScripts and moreStyles equivalents, you have there ready to use samples.
I use a ViewModel approach to solve this issue.
The default ViewModel:
class DefaultPage(
implicit val request: RequestHeader,
implicit val lang: Lang) {
var title: String = null
val styles = mutable.LinkedHashMap.empty[String, Int]
val scripts = mutable.LinkedHashMap.empty[String, Int]
def title(title: String) {
this.title = title
}
def style(style: String)(implicit priority: Int = 500) {
styles.put(style, priority)
}
def script(script: String)(implicit priority: Int = 500) {
scripts.put(script.toString, priority)
}
def translate(message: String, objects: Any*) = Messages(message, objects: _*)
}
Then I have two template tags:
styles.scala.html
#(styles: scala.collection.mutable.Map[String, Int])
#for(style <- styles.toList.sortBy(_._2)) {
<link rel="stylesheet" href="#routes.Assets.at(style._1)" />
}
scripts.scala.html
#(scripts: scala.collection.mutable.Map[String, Int])
#for(script <- scripts.toList.sortBy(_._2)) {
<script async="true" src="#routes.Assets.at(script._1)"></script>
}
My main template:
main.scala.html
#(page: util.view.models.DefaultPage)(content: Html)
#import tags.scripts
#import tags.styles
#page.style("css/vendor/normalize.min.css")(1)
#page.style("css/vendor/formalize.min.css")(1)
#page.style("css/sprites.min.css")(1)
#page.style("css/main.min.css")(1)
#page.style("css/quirks.min.css")(1000)
#page.script("js/vendor/jquery-1.9.1.min.js")(1)
#page.script("js/vendor/jquery.formalize.min.js")(1)
#page.script("js/plugins.min.js")(1)
#page.script("js/main.min.js")(1)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>#page.title</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width" />
#styles(page.styles)
<script src="#routes.Assets.at("js/vendor/modernizr-2.6.2.min.js")"></script>
</head>
<body class="#page.lang.code #page.lang.language #page.lang.country">
#content
#scripts(page.scripts)
</body>
And a sub template:
#(page: util.view.models.ContactUsPage)
#page.title(page.translate("contact.us.title"))
#page.style("css/contact-us.min.css")
#page.script("js/vendor/jquery.expandable-1.1.4.js")
#page.script("js/contact-us.min.js")
#main(page) {
}
You can pass your javascript which is specific to a page as template parameter link