So, I am learning Angular JS from codeschool course "Shaping up with angular js". The guy on the videos says, that wrapping code in (function(){}) is a good habbit.
BUT, when I do that Im getting an error[$injector:modulerr]`. Without this self-called function syntax everything works fine. And it bothers me, why they tell to do this way, and why does it cause error?
Seems that you are missing the (); self executing braces at the end of your anonymous function:
(function(){
// all your code
})();
//^^^--------------add this (); at the closing.
Usually the format should look like this:
angular.module("gemStore", []).controller("StoreController", function () {
var gems = [
{ name: "Dodecahedron", price: 2, desc: "some description", canPurchase: true },
{ name: "Pentagonal gem", price: 5.95, desc: "...", canPurchase: true }
];
this.products = gems;
})
Related
I'm wondering how to display a number in HTML that was created dynamically later on in the code. For instance I initialize the value reportDataLength in data(), and I tested that it was returning the right value by doing a console.log(), but now I want to display this value in HTML?
name: 'notification-tray',
data() {
return {
headers: [
{
text: 'Notifications',
value: 'Body',
width: '380px',
},
],
reportData: [],
reportDataLength: 0,
};
},
async created() {
await this.getReportDataLength();
},
methods: {
async getReportDataLength() {
... this.reportDataLength = this.reportData.length;
console.log(this.reportDataLength);
},
},
};
But obviously when I do something like this,
<span class="d-none">Notification Button</span>
<span class="badge">this.reportDataLength</span>
it doesn't work correctly. The other solutions I saw for similar problems used JQuery, and I feel like there's a simple way to reference this, but I can't seem to find it out.
okay so if you are using pure Javascript , u can use this in your javascript function :
Document.getElementsByClassName('badge').innerHtml=this.reportDataLength ;
otherwise if you are using vue js you can try something like this in your html file :
<span class="badge">{{reportDataLength}}</span>
You can do document.getElementById("ID-HERE").innerHTML = "new stuff", but be warned that setting innerHTML is dangerous.
I'm having a hard time figuring out how to scrape this webpage to get this wedding list into my onepager. It doesn't seem complicated at first but when I get into the code, I just can't get any results.
I've tried ygrab.js, which was fairly simple and got me somewhere but then I can't seem to scrape the images and it only prints the output in the console (not much documentation to go on).
$(function() {
var $listResult = $('#list-result');
var kado = [];
var data = [
{
url: 'https://www.kadolog.com/fr/list/liste-de-mariage-laura-julien',
selector: '.kado-not-full',
loop: true,
result: [{
name: 'photo',
find: '.views-field-field-photo',
grab: {
by: 'attr',
value: 'src'
}
},
{
name: 'title',
find: '.views-field-title .field-content',
grab: {
by: 'text',
value: ''
}
},
{
name: 'description',
find: '.views-field-body .field-content',
grab: {
by: 'text',
value: ''
}
},
{
name: 'price',
find: '.price',
grab: {
by: 'text',
value: ''
}
},
{
name: 'remaining',
find: '.topinfo',
grab: {
by: 'text',
value: ''
}
},
{
name: 'link',
find: '.views-field-nothing .field-content .btn',
grab: {
by: 'attr',
value: 'href'
}
},
],
},
];
ygrab(data, function(result){
console.log(JSON.stringify(result, null, 2)); //photos = undefined
});
Then there's Node.js with Request and Cheerio (and I tried Crawler too), but I have no idea how node works.
var request = require("request");
This gives me an error in the console saying require is not defined. Fair enough, I added require.js to the scripts in my page. I got another error ("Uncaught Error: Mismatched anonymous define() module: ...").
My question is this: Is there a simple Javascript way (possibly without involving node?), to scrape the wedding list I'm trying to get? Or maybe a tutorial that resembles what I'm trying to do step by step ?
I'd be truly grateful for any help or advice.
i think your only issue is the img selector.
Change
{
name: 'photo',
find: '.views-field-field-photo',
grab: {
by: 'attr',
value: 'src'
}
},
To this
{
name: 'photo',
find: '.views-field-field-photo .field-content img',
grab: {
by: 'attr',
value: 'src'
}
},
I actually can't test this right now, but it should be working!!
Node.js is a seperate application that executes javascript independent of a web page.
require is Node's way of importing packages, and isn't defined by the browser, require.js is a javascript library for requiring packages, but it doesn't work the same way as Node's require function.
To use request and cheerio, you'd need to install Node.js from here, then install request and cheerio with the following commands:
npm install request --save
npm install cheerio --save
Then any code you write with Node.js in that directory will have access to the modules.
Here's a tutorial to web scraping in Node.js with cheerio.
I am currently working on a small project where I need to use a bubble chart exactly described in this blog See it here. I want its content to be dynamic, so what I did is to modify it so it would get content from a json page. As I code I encounter an error exactly described Here. I followed the solution from it but I got an error its says "Uncaught TypeError: Cannot read property 'items' of undefined". I can't comment on the issue since I dont have enough reputation so I created a new question instead.
here is the original code from D3(index.js, ellipsis to shorten code):
$(document).ready(function () {
var bubbleChart = new d3.svg.BubbleChart({
supportResponsive: true,
size: 600,
...
data: {
items: [
{text: "Java", count: "236"},
{text: ".Net", count: "382"},
{text: "Php", count: "170"},
...
{text: "Something", count: "170"},
],
eval: function (item) {return item.count;},
classed: function (item) {return item.text.split(" ").join("");}
},
plugins: [
{
...
},
{
...
}] });
});
Here is my updated code as suggested from the link I mentioned earlier:
$(document).ready(function () {
d3.json("http://json/path/", function (json) {
var bubbleChart = new d3.svg.BubbleChart({
supportResponsive: true,
size: 600,
...
data:json,
plugins: [
{
...
},
{
...
}]
});
});
});
It seems the error prompted because the lines below were removed however I tried to modify the code above to incorporate the code below but I got no luck to make it work. it seems these code is still needed in bubble-chart.js. I already checked my json strings and it is valid.
eval: function (item) {return item.count;},
classed: function (item) {return item.text.split(" ").join("");}
Is there anyone can help me solve this? any help would be appreciated. Thank you!
-Borj
I'm currently trying out angularJS to see how it works.
I followed a tutorial on egghead.io which is quite good.
Came up with this fiddle but it annoys me that I cant find the issue/error.
Nothing shows/outputs
app.js
(function() {
var app = angular.module('gemStore', []);
app.controller('StoreController', function() {
this.products = gems;
});
var gems = [
{
name: "Soap",
price: 25,
quantity: 10,
canPurchase: false
},
{
name: "Bag",
price: 100,
quantity: 15,
canPurchase: false
}
];
});
index
<body ng-controller="StoreController as store">
<div ng-repeat="product in store.products">
<h1>{{product.name}}</h1>
<h2>${{product.price}}</h2>
<button ng-show="product.canPurchase">Add to cart</button>
</div>
This is the fiddle: https://jsfiddle.net/Vwsej/618/ (UPDATED)
Hope you could point me in the right direction.
In advance, thanks.
You forgot to include angular in your page. Simply add:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
to your HTML page. Note that jsfiddle has a button on the top left under "Frameworks & Extensions" that allows you to quick-add libraries such as angular.
You also forgot to call your IIFE:
(function() {
//Your JS...
})(); //<--- you forgot the ()
I forked your fiddle and fixed those issues, it works just fine.
You forgot to call the self calling function:
JS Fiddle:
https://jsfiddle.net/Vwsej/620/
This is how self calling structure is:
(function(){
// your js code to execute
})();//forgot to call
I've been working on the CodeSchool AngularJS app, which I've understand so far, but when I began using dependency injections, specifically, $http in order to make an call for my JSON data the app stops working, and I don't know why. Originally with the first line uncommented the app worked as it should using the variable gems declared within the closure, which is exactly the same code now found in products.json. I commented out the first line of the controller, and added the appropriate changes to for dependency injection, but now the app doesn't load at all, and it throws the error found below (also see $http-injection.png).
app.controller('StoreController', [ '$http', function($http) {
//this.products = gems; <-- works like this with data in closure
var store = this;
store.products = [ ]; // no erros on page load
$http.get('/data/products.json').success(function( data ) {
store.products = data;
});
}]);
Error: [ngRepeat:dupes] http://errors.angularjs.org/1.3.0-beta.10/ngRepeat/dupes?p0=product%20in%20storeCtrl.products&p1=string%3A%0D
at Error (native)
at http://angularjs.dev/angular-1.3/angular.min.js:6:457
at http://angularjs.dev/angular-1.3/angular.min.js:204:24
at Object.<anonymous> (http://angularjs.dev/angular-1.3/angular.min.js:108:144)
at Object.applyFunction [as fn] (<anonymous>:778:50)
at g.$digest (http://angularjs.dev/angular-1.3/angular.min.js:109:211)
at g.$delegate.__proto__.$digest (<anonymous>:844:31)
at g.$apply (http://angularjs.dev/angular-1.3/angular.min.js:112:325)
at g.$delegate.__proto__.$apply (<anonymous>:855:30)
at g (http://angularjs.dev/angular-1.3/angular.min.js:73:287) angular.js:10811
(anonymous function) angular.js:10811
(anonymous function) angular.js:7962
g.$digest angular.js:12560
$delegate.__proto__.$digest VM8634:844
g.$apply angular.js:12858
$delegate.__proto__.$apply VM8634:855
g angular.js:7380
x angular.js:8527
y.onreadystatechange
product.json
[
{
name: 'Hexagonal',
price: 250.00,
description: 'The six faces of the hexaonal gem have a habit to excite the eye, and attract good luck.',
canPurchase: true,
soldOut: false,
images: [ ],
reviews: [
{
stars: 5,
body: "I love this product!",
author: "mtpultz#gmail.com"
},
{
stars: 1,
body: "This product sucks!",
author: "mtpultz#hater.com"
}
]
},
{
name: 'Dodecahedron',
price: 1015.25,
description: 'Some gems have hidden qualities beyond their luster, beyond their shine... Dodeca is one of those gems.',
canPurchase: true,
soldOut: false,
images: [
"img/gem-06.gif",
"img/gem-02.gif",
"img/gem-01.gif"
],
reviews: [
{
stars: 3,
body: "I think this gem was just OK, could honestly use more shine, IMO.",
author: "mtpultz#hotmail.com"
},
{
stars: 4,
body: "Any gem with 12 faces is for me!",
author: "mtpultz#casensitive.ca"
}
]
},
{
name: 'Pentagonal Gem',
price: 5.95,
description: 'Origin of the Pentagonal Gem is unknown, hence its low value. It has a very high shine and 12 sides however.',
canPurchase: true,
soldOut: false,
images: [
"img/gem-02.gif",
"img/gem-06.gif",
"img/gem-01.gif"
],
reviews: [
{
stars: 4,
body: "The mystery of the Pentagonal Gem makes it sooo fascinating!",
author: "mtpultz#peanutbutter.com"
},
{
stars: 5,
body: "I can't get enough of the five faces of the Pentagonal Gem!",
author: "mtpultz#ketchup.ca"
}
]
}
];
Originally I was going to try and figure out how to use $log as well, and when I had $log injected it appears as if the json is received (see $http-and-$log-injection.png attached) based on the chrome batarang plugin's output, but the app still doesn't work either way, only the JSON appears on right side of batarang output.
app.controller('StoreController', [ '$http', '$log', function($http, $log) {
//this.products = gems;
var store = this;
store.products = [ ]; // no erros on page load
$http.get('/data/products.json').success(function( data ) {
store.products = data;
});
}]);
You shouldn't use the minified version of Angular while developing. You'll get better error messages when using the non-minified version. But even when you're using the minified version you can get a pretty good idea of what the problem is by visiting the url mentioned first in the exception: http://errors.angularjs.org/1.3.0-beta.10/ngRepeat/dupes?p0=product%20in%20storeCtrl.products&p1=string%3A%0D
It seems like you have duplicates in products.json. Without seeing the whole contents of products.json or any of your markup that would be my best guess.
--
Update: It seems like data is a string and not an array. This is probably because the response body from the server is not properly formatted JSON. Instead of traversing objects in an array, ng-repeat traverses characters in a string and throws an error on the second tab character (encoded as %0D) it detects. I've created a plnkr with properly and a bad response as an example: http://plnkr.co/edit/XbPuXkykzv36NyH3sSeu?p=preview
You should use $scope:
$scope.store = {};
$scope.store.products = [ ]; // no erros on page load
$http.get('/data/products.json').success(function( data ) {
$scope.store.products = data;
});
ngRepeat:dupes error occurs if there are duplicate keys(values in your array/json) in an ng-repeat expression, this is because AngularJS uses keys to associate DOM node with ng-repeated items. The requested data products.json may have fields that contain the same value, to solve this, you can append a track by $index expression in your ng-repeat so that the association of DOM node items will be keyed by the index of the your array/json instead of the value of each item.
E.G.
<div ng-repeat="product in Store.products track by $index"></div>