Angular2 displaying data example not working - javascript

I am following the tutorial on Angular2 from https://angular.io/docs/js/latest/guide/displaying-data.html but it is not working for me. Let me know what I am missing here.
BTW - I am using ES5 only.
Code in index.html -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Angular2 Demo</title>
<!-- 1. Load libraries -->
<!-- IE required polyfill -->
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/rxjs/bundles/Rx.umd.js"></script>
<script src="node_modules/angular2/bundles/angular2-all.umd.js"></script>
<script src="app/component.js"></script>
</head>
<body>
<display></display>
</body>
</html>
In component.js -
function DisplayComponent() {
this.myName = "Alice";
}
DisplayComponent.annotations = [
new angular.ComponentAnnotation({
selector: "display"
}),
new angular.ViewAnnotation({
template:
'<p>My name: {{ myName }}</p>'
})
];
Error I am getting if I am running idex.html in browser -
ReferenceError: angular is not defined

The sample doesn't seem to be correct... You should use the ComponentMetadata and ViewMetadata object:
function DisplayComponent() {
this.myName = "Alice";
}
DisplayComponent.annotations = [
new ng.core.ComponentMetadata({
selector: "display"
}),
new ng.core.ViewMetadata({
template:
'<p>My name: {{ myName }}</p>'
})
];
See this plunkr for more details: https://plnkr.co/edit/biMKXl1WXsgTCxbjwcme?p=preview.
You could also use the ng.core.Component object as described below:
var DisplayComponent = ng.core.
Component({
selector: "display"
})
.View({
template:
'<p>My name: {{ myName }}</p>'
})
.Class({
constructor: function() {
this.myName = "Alice";
}
});
See this plunkr: https://plnkr.co/edit/73Hirx9aqnITZCPonltX?p=preview.
This link could give you some hints:
Even better ES5 code for Angular 2 - http://blog.thoughtram.io/angular/2015/07/06/even-better-es5-code-for-angular-2.html

Related

Uncaught ReferenceError: characters is not defined

I am creating a simple rest api in javascript, I want upon initialization, the widget must display a list of all characters.
here is folder structure :
├───book
└───book.js
├───store
│ └───store.js
here is my store.js
window.Store = {
create: function() {
var self = {};
var props = {
name: 'string',
species: 'string',
picture: 'string',
description: 'string'
};
var listProps = ['name', 'species'];
var detailProps = ['name', 'species', 'picture', 'description'];
var characters = [
{
id: makeID(),
name: 'Ndiefi',
species: 'Wookie',
picture: 'store/img/ndiefi.png',
description: 'A legendary Wookiee warrior and Han Solo’s co-pilot aboard the Millennium Falcon, Chewbacca was part of a core group of Rebels who restored freedom to the galaxy. Known for his short temper and accuracy with a bowcaster, Chewie also has a big heart -- and is unwavering in his loyalty to his friends. He has stuck with Han through years of turmoil that have changed both the galaxy and their lives.',
_delay: 500
},
];
}
}
here is index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Character Book</title>
<!-- 3rd party vendor libraries -->
<link rel="stylesheet" href="vendor/font-awesome-4.6.3/css/font-awesome.min.css">
<script src="vendor/jquery-3.1.0.min.js"></script>
<script src="vendor/underscore-1.8.3.min.js"></script>
<!-- 1st party internal libraries -->
<script src="store/store.js"></script>
<script src="tests/start-test.js"></script>
<script src="tests/test-book.js"></script>
<!-- The source of the 'Book' widget -->
<link href="book/book.css" rel="stylesheet">
<script src="book/book.js"></script>
<script>
$(function() {
var frame = $('#test-frame');
var run = $('#test-run');
var results = $('#test-results');
var store = Store.create();
run.click(function() {
run.prop('disabled', true).text('Running Tests');
results.removeClass('test-pass test-fail').text('');
testBook(frame).then(
function success() {
run.prop('disabled', false).text('Run Tests');
results.addClass('test-pass').text('All tests passed');
},
function failure(err) {
run.prop('disabled', false).text('Run Tests');
results.addClass('test-fail').text('Test failed, see console');
}
);
});
Book.init(frame, store);
});
</script>
</head>
<body>
<button id="test-run">Run Tests</button>
<span id="test-results"></span>
<div id="test-frame">
</div>
</body>
</html>
here is what I have tried :
books.js
var data = JSON.parse(characters);
data.forEach(characters => {
console.log(characters.name)
});
so when I run the app in my browser I see the following error :
Uncaught ReferenceError: characters is not defined
what is wrong with my code ? any suggestion or help will be helpfull thanks

Vuejs will not render component correctly when trying to loop thru array data or v-for

<!DOCTYPE html>
<html lang="en">
<head>
<script src="js/vue.js"></script>
<meta charset="UTF-8">
<title>V-for example</title>
</head>
<body>
<script type="x/template" id="testTemplate">
<div><h1>{{name}}</h1>
<p>{{Age}}</p></div>
</script>
<div id="example">
<div id="filler">
<template v-for="person in people">
<test-component name="{{person.name}}"></test-component>
</template>
</div>
</div>
<script>
var newComponent = Vue.extend({
template: '#testTemplate',
props: ['name'],
data: function () {
return {
Age: 1010
}
}
});
Vue.component('test-component', newComponent);
new Vue({
el: '#example',
data: {
people: [{
name: 'jason',
age: 15,
complete: true
}, {
name: 'Jeremy',
age: 20,
complete: false
}]
},
ready: function () {
var divoutput = document.querySelector('#filler');
alert(divoutput.innerHTML);
len = this.$data.people.length;
for (i = 0; i < len; i += 1) {
var nameT = this.$data.people[i].name;
divoutput.innerHTML += '<test-component name="' + nameT + '"></test-component>';
}
},
});
</script>
</body> </html>
I'm trying to take all of the people in the Vue data array and inject it into a component and add it to a innerHTML of a div during the Vue.ready() function. I show that result is being injected in to the "filler" array but the components them selves are not being rendered properly. If I make a manual instance of my component it works fine.
You shouldn't try to add Vue component using innerHTML. That's managing the DOM yourself, just let Vue do that on its own. Here is a fiddle:
https://jsfiddle.net/xccjsp4b/
I changed the script template to a div because I'm not certain you can use the script tag like that (although I could be wrong). Then you just use a v-for to loop through the people and pass the relevant data as properties. If each person is going to have their own age, you want it to be a property not a data variable.
Also, use the shorthand binding of :name="person.name" rather than name="{{person.name}}". The : tells Vue to evaluate the expression.

Polymer 1.0 Data Binding with inline script tags

Is this possible to have data binding inside an inline script tag? For example:
<script src="{{url}}" class="{{klass}}"></script>
Polymer({
is: "test-app",
ready: function() {
url = "http://google.com/js/some-file.js",
klass = "script-class"
}
});
Based on the Polymer 1.0 Data Binding docs, I could not come up with anything better.
I have edited this post to 100% clarity of what I want to achieve. I want to use Strip Embedded Checkout:
<form action="" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_blahblah"
data-amount="2000"
data-name="Demo Site"
data-description="2 widgets ($20.00)"
data-image="/128x128.png">
</script>
</form>
Mason's answer and Anthony's clue led me to this:
<dom-module id="my-app>
<template>
<form action="" method="POST">
<script
src$="{{url}}" class$="{{klass}}"
data-key$="{{key}}"
data-amount$="{{total}}"
data-name$="{{dname}}"
data-description="2 widgets ($20.00)"
data-image="/128x128.png">
</script>
</form>
</template>
<script>
Polymer({
is: "my-app",
properties: {
selection: {
type: String,
observation: "selectionChanged"
}
},
ready: function() {
this.url = 'https://checkout.stripe.com/checkout.js';
this.klass = 'stripe-button';
this.key = 'pk_test_blahblah';
this.dname = 'Demo';
// this.total = "333"; // this value is not static
},
selectionChanged: function () {
if (true) {
this.total = 50; // I need this to assign to "{{total}}" in the template.
}
};
</script>
</dom-module>
How can I get the value of this.total to be assigned to data-amount in the script tag of Stripe's?
See Plunkr
I did a Plunk and it seems it's not possible to do this.
<dom-module id="my-element">
<template>
<script src="{{url}}"></script>
Try to load <span>{{name}}</span>
</template>
<script>
Polymer({
is: 'my-element',
ready: function() {
this.name = 'JQuery';
this.url = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';
this.async(function() {
this.name = 'AngularJs';
this.url = 'https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js';
}, 5000);
}
});
</script>
</dom-module>
The first loading works but when the bind value has changed, Polymer does not create a new script tag for you. You can create a script tag by using the DOM.
Edited:
Initializing the script tag's attributes without "ready" method.
<template>
<script src="{{_url}}"></script>
</template>
<script>
Polymer({
is: 'my-element',
properties: {
_url: {
type: String,
value: 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js'
}
}
})
</script>
Or using hosted attributes
<template>
<script src="{{url}}"></script>
Try to load <span>{{name}}</span>
</template>
<script>
Polymer({
is: 'my-element',
hostAttributes: {
url: {
type: String
}
}
})
</script>
and in the parent element:
<my-element url="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></my-element>
By using hostAttributes you'll see the url in the DOM.

How can I access the attribute from the template?

In this example i'm expecting it to say "hello world" but the world isn't picked up from the saying attribute.
(function () {
'use strict';
$(function () {
// Set up a route that maps to the `filter` attribute
can.route(':filter');
// Render #app-template
$('#app').html(can.view('appTemplate', {}));
// Start the router
can.route.ready();
});
can.Component.extend({
tag: "say",
scope: {
saying: function(){
return this.attr('saying')
},
greeting: 'salutations'
},
template: can.view("sayTemplate")
});
})();
Templates:
<div id="app"></div>
<script id="appTemplate" type="text/mustache">
<b>Hello</b>
<say saying="world"></say>
</script>
<script id="sayTemplate" type="text/mustache">
<b>{{saying}}.</b> <i>{{greeting}}</i>
</script>
You need to tell the component that you want to access the attributes plain value like this:
can.Component.extend({
tag: "app-say",
scope: {
saying: '#',
greeting: 'salutations'
},
template: can.view("sayTemplate")
});
See this Fiddle. What you eventually might want to do use an observable attribute from your application state instead of the plain string value. This might look like:
var appState = new can.Map({
name: 'World'
});
$(function () {
// Set up a route that maps to the `filter` attribute
can.route(':filter');
// Render #app-template
$('#app').html(can.view('appTemplate', appState));
// Start the router
can.route.ready();
});
can.Component.extend({
tag: "app-say",
scope: {
greeting: 'salutations'
},
template: can.view("sayTemplate")
});
And a template like:
<div id="app"></div>
<script id="appTemplate" type="text/mustache">
<b>Hello</b>
<app-say saying="{name}"></app-say>
<div><input type="text" can-value="name"></div>
</script>
<script id="sayTemplate" type="text/mustache">
<b>{{saying}}.</b> <i>{{greeting}}</i>
</script>
This also creates a cross-bound input field that will update the name everywhere whenever you update the text field. Fiddle is here.

backbone error while trying to reset a collection

I am doing a very simple Backbone app example and I keep getting a JS error message. I basically have two files:
app.js
This file creates a Backbone.js app the appends a span from a template using data from a collection view to an already created div on the html file.
/*Backbone.js Appointments App*/
App = (function($){
//Create Appointment Model
var Appointment = Backbone.Model.extend({});
//Create Appointments Collection
var Appointments = Backbone.Collection.extend({
model: Appointment
});
//Instantiate Appointments Collection
var appointmentList = new Appointments();
appointmentList.reset(
[{startDate: '2013-01-11', title: 'First Appointment', description: 'None', id: 1},
{startDate: '2013-02-21', title: 'Second Appointment', description: 'None', id: 2},
{startDate: '2013-02-26', title: 'Third Appointment', description: 'None', id: 3}
]
);
//Create Appointment View
var AppointmentView = Backbone.View.extend({
template: _.template(
'<span class="appointment" title="<%= description %>">' +
' <span class="title"><%= title %></span>' +
' <span class="delete">X</span>' +
'</span>'
),
initialize: function(options) {
this.container = $('#container');
},
render: function() {
$(this.el).html(this.template(this.model));
this.container.append(this.el);
return this;
}
});
var self = {};
self.start = function(){
new AppointmentView({collection: appointmentList}).render();
};
return self;
});
$(function(){
new App(jQuery).start();
});
index.html
This file just calls the jquery, backbone and other js libraries and also created the div container where the Backbone.js app from the previous file will append the data.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>hello-backbonejs</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
<script src="app.js" type="text/javascript"></script>
</head>
<body>
<div id="container"></div>
</body>
</html>
The error I get is the following:
Uncaught TypeError: Object [object Object] has no method 'reset' app.js:14
App app.js:14
(anonymous function) app.js:49
e.resolveWith jquery.min.js:16
e.extend.ready jquery.min.js:16
c.addEventListener.z jquery.min.js:16
You use Backbone 0.3.3 but Collection.reset was introduced in Backbone 0.5. See the changelog for more information.
Either upgrade Backbone (0.9.9 at the moment) (and Underscore and jQuery while you're at it) or use Collection#refresh if you absolutely have to keep Backbone 0.3.3 (but you will probably trip other errors down the road).

Categories

Resources