Angular Js : Simple app not working - javascript

I am learning AngularJS from codeSchool and I was making a simple hello world app , initially it was being rendered properly but after some time It didn't work at all. I am not able to detect the bug , please help
Here is the code for html file
<!DOCTYPE html>
<html ng-app="store">
<head>
<title>Angular Code School</title>
<link rel="stylesheet" href="bootstrap.min.css">
</head>
<body>
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript" src="app.js"></script>
I am {{4+6}}
{{"Hello +"World"}}
<div ng-controller="StoreCtrl as store">
<div ng-repeat="product in store.products| orderBy:'-price'">
<h2>Name :{{product.name}} </h2>
<h2>Price:{{product.price | currency}} </h2>
<h2>Description:{{product.description}} </h2>
<button ng-show="product.canPurchase">Add To Cart </button>
<section ng-controller="PanelCtrl as panel">
<ul class="nav nav-pills">
<li ng-class="{'active':panel.isSelectedTab(1)}"><a href ng-click="panel.selectTab(1)"> Description</a></li>
<li ng-class="{'active':panel.isSelectedTab(2)}"><a href ng-click="panel.selectTab(2)">Specs</a></li>
<li ng-class="{'active':panel.isSelectedTab(3)}"><a href ng-click="panel.selectTab(3)">Reviews</a></li>
</ul>
<div ng-show="panel.isSelectedTab(1)">This is description div</div>
<div ng-show="panel.isSelectedTab(2)">This is Specification Section</div>
<div ng-show="panel.isSelectedTab(3)">This is Reviews section</div>
</section>
</div>
</div>
</body>
</html>
appTest.js
var app = angular.module('store', []);
app.controller('StoreCtrl', ['$scope', function ($scope) {
this.products = gems;
}])
gems = [{
name: 'Dodecahedron',
price: 2.95,
description: 'This is the description of Dodecahedron'
canPurchase: false;
},
{
name:'Diamond',
price: 5.95,
description: 'Diamond is the most luxuriest gem of all.'
canPurchase:true;
}]
app.controller('PanelCtrl', ['$scope', function ($scope) {
this.tab=1;
this.selectTab = function(setTab) {
this.tab = setTab;
};
this.isSelectedTab = function(checkTab){
return this.tab===checkTab;
}
}])
The structure of my directory is like
root/
angular.js
appTest.js
index.html
Here is the page with console

appTest.js
var app = angular.module('store', []);
app.controller('StoreCtrl', function() {
this.products = gems;
});
app.controller('PanelCtrl', function() {
this.tab = 1;
this.selectTab = function(setTab) {
this.tab = setTab;
};
this.isSelected = function(checkTab) {
return this.tab === checkTab;
};
});
var gems =
[{
name: 'Dodecahedron',
price: 2.95,
description: 'This is the description of Dodecahedron',
canPurchase: false
},
{
name: 'Diamond',
price: 5.95,
description: 'Diamond is the most luxuriest gem of all.',
canPurchase: false
}];
and in index.html
{{"Hello" +"World"}} should be {{"Hello" + "World"}}

You're messing a double quote:
{{"Hello +"World"}}
should be:
{{"Hello " + "World"}}
Check your console for javascript error.

Three issues:
Modify the hello words as below
{{ "Hello" + "World"}}
in your appTest.js,
add the comma after description fields of the 'gem'
remove the ";" semicolon after "canPurchase"
in your html file
ensure you are including "appTest.js" and not just "app.js"

Related

ng-options inside ng-repeat - can't access selected item in $scope

I want to do the following:
I have an array of all possible items 'all'.
I want to create a subset of that array in 'subset':
js.js:
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
$scope.all = [];
$scope.subset = [{name: 'n1', inUse: false}, {name: 'n2', inUse: false}, {name: 'n3', inUse: false} ];
// adding new item in all
$scope.addItem = function() {
var newc = {name: '?', inUse: false};
$scope.all.push(newc);
};
$scope.updateC = function(index) {
// index refers to all array
$scope.all[index].inUse = false;
$scope.all[index] = $scope.selectedItem;
$scope.all[index].inUse = true;
};
});
HTML.html:
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<script type="text/javascript" src="angular-1.4.8.js"></script>
<script type="text/javascript" src="js.js"></script>
</head>
<body ng-controller="myController">
<button ng-click="addItem()">Add Item: </button>
<div ng-repeat="c in all">
{{c.name}}
<select ng-options="c as c.name for c in subset | filter: {inUse: false}"
ng-change="updateC($index)"
ng-model="selectedItem"></select>
</div>
</body>
</html>
But I'm getting 'TypeError: Cannot set property 'inUse' of undefined'. I see the inUse property in a child scope. Is that behaviour expected? How can I access the selected item in my scope?
I can do the following, but I don't believe it's correct:
var child = $scope.$$childHead;
for (var i = 0; i < index ; i++) {
child = child.$$nextSibling;
}
$scope.all[index] = child.selectedItem;
What is the correct way of doing what I want?
Charlie, you gave me the idea of changing the way I'm adding items to the subset:
JS
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
$scope.subset = [];
$scope.all = [{name: 'n1', inUse: false}, {name: 'n2', inUse: false}, {name: 'n3', inUse: false} ];
// adding new item in all
$scope.addItem = function() {
if ($scope.selectedItem != null) {
$scope.selectedItem.inUse = true;
$scope.subset.push($scope.selectedItem);
}
};
});
It's not the same I wanted to do, but it works.
HTML
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<script type="text/javascript" src="angular-1.4.8.js"></script>
<script type="text/javascript" src="js.js"></script>
</head>
<body ng-controller="myController">
<select ng-options="c2 as c2.name for c2 in all | filter: {inUse: false}"
ng-model="selectedItem"></select>
<button ng-click="addItem()">Add Item: </button>
<div ng-repeat="c in subset">
{{c.name}}
</div>
</body>
</html>

Issues with AngularJS Service

I´m currently starting to learn Angular.JS and worked with a few tutorials like this this one. I followed the Steps but tryed to improve the code by saving single parts like controllers or services in seperate .js files because I heared this is a good habit. That was no problem and all worked fine. But when I came up with the Service which provides my posts I also tried to write some sort of API in the Service because i learned in another tutorial to do so.
There comes the Problem: The API to get my list of posts is working fine but if I try to send data due to an addPost function to the API it doesn´t work at all.
So can you maybe help me to find out what the problem is because I want to implement a Backend to the post-Service later on and want all $http requests at one place.
EDIT
The code-sample below is running now and you can see the problem if you try to add a post. The code stops after/during the addPost() function in the MainCtrl because the "clearing" of the HTML-form isn´t happening.
here you can find my code:
var app = angular.module('flapperNews', []);
app.controller('MainCtrl', function($scope, postService){
$scope.test = "Hello, World!";
$scope.posts = postService.getPosts();
$scope.addPost = function(){
if(!$scope.title || $scope.title === '') { return; }
postService.addPost({title: $scope.title, link: $scope.link, upvotes: 0});
//This code above was my try ith the API in posts.js
// $scope.posts.push({
// title: $scope.title,
// link: $scope.link, // this whole part is from the tutorial and works fine
// upvotes: 0
//});
$scope.title = '';
$scope.link = '';
};
$scope.incrementUpvotes = function(post) {
post.upvotes += 1;
};
});
app.factory('postService', function() {
var srv = {};
srv._posts = [
{title: 'post 1', link: '', upvotes: 5},
{title: 'post 2', link: '', upvotes: 2},
{title: 'post 3', link: '', upvotes: 15},
{title: 'post 4', link: '', upvotes: 9},
{title: 'post 5', link: '', upvotes: 4}
];
srv.getPosts = function() {
return angular.copy(srv._posts);
};
srv.addPost = function(post) { //function to put the new Post in the Array
srv._posts.push(post);
};
return {
getPosts: function() {
return srv.getPosts();
},
addPost: function(post) { //the public API to put the post in the Array
srv.addPost(post);
}
};
});
<!DOCTYPE html>
<html>
<head>
<meta charset="Utf-8">
<title>FlapperNews</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<style> .glyphicon-thumbs-up { cursor:pointer } </style>
</head>
<body ng-app="flapperNews" ng-controller="MainCtrl">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="page-header">
<h1>Flapper News</h1>
</div>
<div ng-repeat="post in posts | orderBy:'-upvotes'">
<span class="glyphicon glyphicon-thumbs-up"
ng-click="incrementUpvotes(post)"></span>
{{post.upvotes}}
<span style="font-size:20px; margin-left:10px;">
<a ng-show="post.link" href="{{post.link}}">
{{post.title}}
</a>
<span ng-hide="post.link">
{{post.title}}
</span>
</span>
</div>
<form ng-submit="addPost()"
style="margin-top:30px;">
<h3>Add a new post</h3>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Title"
ng-model="title"></input>
</div>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Link"
ng-model="link"></input>
</div>
<button type="submit" class="btn btn-primary">Post</button>
</form>
</div>
</div>
<!-- Scripts -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src=scripts/app.js></script>
<script src=scripts/controller/main.js></script>
<script src=scripts/service/posts.js></script>
</body>
</html>
Once you push the data to the service you should update $scope.posts
$scope.addPost = function(){
if(!$scope.title || $scope.title === '') { return; }
postService.addPost({title: $scope.title, link: scope.link, upvotes: 0});
$scope.posts = postService.getPosts();
// or edit postService.addPost so you can make
/* $scope.posts = postService.addPost({title: $scope.title, link: scope.link, upvotes: 0}); */
$scope.title = '';
$scope.link = '';
};

Angular JS Binding not working

I am not sure what is going wrong in the following code - but it doesn't seems working. can anyone help?
<body ng-controller="MyFunction">
<script>
function MyFunction($scope) {
$scope.author = {
'name':'Test',
'title': 'Mr',
'Job': 'SDE'
}
}
</script>
<h2> {{author.name}} </h2>
<h2> {{author.title + " " + author.Job}} </h2>
</body>
Here you are. You are incorrect in structure of angularjs, I don't see the ng-app and wrong to declare controller:
angular.module('app', []).controller('MyFunction', function($scope) {
$scope.author = {
'name': 'Test',
'title': 'Mr',
'Job': 'SDE'
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app='app' ng-controller="MyFunction">
<h2> {{author.name}} </h2>
<h2> {{author.title + " " + author.Job}} </h2>
</body>
Hope this helps.
There is several things wrong with your code. You are missing an ng-app declaration, you are missing a module to use for that declaration and you did not register your controller correctly. Your example in a working state:
function authorInfoController() {
this.author = {
name: 'Amadeus Smith',
title: 'Prof.',
job: 'Super Senior Cloud Advisor Managment Consultant'
};
}
angular.module("myApp", [])
.controller("AuthorInfoCtrl", authorInfoController);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
<div ng-app="myApp" ng-controller="AuthorInfoCtrl as info">
<h2>{{info.author.name}}</h2>
<h2>{{info.author.title + " " + info.author.job}}</h2>
</div>
If you are just learning angular, I recommend doing a good tutorial and reading a styleguide.

Adding child routes in ember.js

I'm working on ember.js tutorial now. I got a problem on "adding child routes" chapter. My todos list is not displayed. The "todos" template outputing just fine but "todos/index" template doesn't work at all. The console does not show any errors. I guess that this is some local problem or some bug. Maybe someone has already met with a similar problem. What could be the reason of this issue? How can i solve it?
Thanks.
HTML:
<html>
<head>
<meta charset="utf-8">
<title>Ember.js • TodoMVC</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script type="text/x-handlebars" data-template-name="todos/index">
<ul id="todo-list">
{{#each itemController="todo"}}
<li {{bind-attr class="isCompleted:completed isEditing:editing"}}>
{{#if isEditing}}
{{edit-todo class="edit" value=title focus-out="acceptChanges" insert-newline="acceptChanges"}}
{{else}}
{{input type="checkbox" checked=isCompleted class="toggle"}}
<label {{action "editTodo" on="doubleClick"}}>{{title}}</label><button {{action "removeTodo"}} class="destroy"></button>
{{/if}}
</li>
{{/each}}
</ul>
</script>
<script type="text/x-handlebars" data-template-name="todos">
<section id="todoapp">
<header id="header">
<h1>todos</h1>
{{input type="text" id="new-todo" placeholder="What needs to be done?"
value=newTitle action="createTodo"}}
</header>
<section id="main">
{{outlet}}
<input type="checkbox" id="toggle-all">
</section>
<footer id="footer">
<span id="todo-count">
<strong>{{remaining}}</strong> {{inflection}} left</span>
<ul id="filters">
<li>
All
</li>
<li>
Active
</li>
<li>
Completed
</li>
</ul>
<button id="clear-completed">
Clear completed (1)
</button>
</footer>
</section>
<footer id="info">
<p>Double-click to edit a todo</p>
</footer>
</script>
<script src="js/libs/jquery-1.10.2.js"></script>
<script src="js/libs/handlebars-1.1.2.js"></script>
<script src="js/libs/ember-1.2.0.js"></script>
<script src="js/libs/ember-data.js"></script>
<script src="js/app.js"></script>
<script src="js/route.js"></script>
<script src="js/models/todo.js"></script>
<script src="js/controllers/todo_controller.js"></script>
<script src="js/controllers/todos_controller.js"></script>
<script src="js/views/edit_todo_view.js"></script>
</body>
</html>
JS:
window.Todos = Ember.Application.create();
Todos.ApplicationAdapter = DS.FixtureAdapter.extend();
Todos.Router.reopen({
rootURL: '/one/'
});
Todos.Router.map(function () {
this.resource('todos', { path: '/' });
});
Todos.TodosRoute = Ember.Route.extend({
model: function () {
return this.store.find('todo');
}
});
Todos.TodosIndexRoute = Ember.Route.extend({
model: function () {
return this.modelFor('todos');
}
});
Todos.Todo = DS.Model.extend({
title:DS.attr('string'),
isCompleted:DS.attr('boolean')
});
Todos.Todo.FIXTURES = [
{
id: 1,
title: 'Learn Ember.js',
isCompleted: true
},
{
id: 2,
title: '...',
isCompleted: false
},
{
id: 3,
title: 'Profit!',
isCompleted: false
}
];
Todos.TodosController = Ember.ArrayController.extend({
actions: {
createTodo: function () {
// Get the todo title set by the "New Todo" text field
var title = this.get('newTitle');
if (!title.trim()) { return; }
// Create the new Todo model
var todo = this.store.createRecord('todo', {
title: title,
isCompleted: false
});
// Clear the "New Todo" text field
this.set('newTitle', '');
// Save the new model
todo.save();
}
},
remaining: function () {
return this.filterBy('isCompleted', false).get('length');
}.property('#each.isCompleted'),
inflection: function () {
var remaining = this.get('remaining');
return remaining === 1 ? 'item' : 'items';
}.property('remaining'),
});
Todos.TodoController = Ember.ObjectController.extend({
actions:{
editTodo: function () {
this.set('isEditing', true);
},
acceptChanges: function () {
this.set('isEditing', false);
if (Ember.isEmpty(this.get('model.title'))) {
this.send('removeTodo');
} else {
this.get('model').save();
}
},
removeTodo: function () {
var todo = this.get('model');
todo.deleteRecord();
todo.save();
},
},
isEditing: false,
isCompleted: function(key, value){
var model = this.get('model');
if (value === undefined) {
// property being used as a getter
return model.get('isCompleted');
} else {
// property being used as a setter
model.set('isCompleted', value);
model.save();
return value;
}
}.property('model.isCompleted')
});
Technically this isn't a bug, the team figured there is no point in having an index route if you can't go any deeper in the router (this is due to the fact that the todos route and template will render, so there is no real need for the index route. That being said, if you really want it, add an anonymous function and you'll get it.
Todos.Router.map(function () {
this.resource('todos', { path: '/' },function () {});
});
https://github.com/emberjs/ember.js/issues/3995
I had this problem too. After much perplexity, the solution was to use a version of index.html that actually had the <script> wrapped <ul>, instead of the one where I was moving that block around to see if it made a difference and ended up having it nowhere.

AngularJS Error: Unknown provider

I'm getting the classic the classic Error: Unknown provider: UserModelProvider <- UserModel with angular JS. My code looks like this:
var ClabborApp = angular.module('clabbor', []);
ClabborApp.factory('UserModel', function() {
var UserModel = {};
var list = [];
UserModel.getItem = function(index) {
return list[index];
}
UserModel.addItem = function(item) {
list.push(item);
}
UserModel.removeItem = function(item) {
list.splice(list.indexOf(item), 1)
}
UserModel.size = function() {
return list.length;
}
return UserModel;
});
function FollowersCtrl($scope, UserModel) {
$scope.followers = [{
text : 'learn angular',
done : true,
'name' : 'James'
}, {
text : 'build an angular app',
done : false,
'name' : 'John'
}];
}
And my html looks like this:
<html lang="en" ng-app>
<meta charset="utf-8">
<body ng-app="clabbor">
<div class="content follow" ng-controller="FollowersCtrl">
<ul class="clearfix">
<!-- Show max 12 followers -->
<li ng-repeat="follower in followers">
{{follower.name}}
</li>
</ul>
</div>
</body>
</html>
I thought I did it by the book but I am getting the error. Does anyone know what could it be?
Remove the ng-app attribute from the html tag. Here's Jsfiddle that's working: http://jsfiddle.net/eA2xx/. You can't have more than one ng-app.

Categories