The page of this app just loads blank. I i searched the problem for hours and still can't find the problem. Angular is 1.3.5 and Angular-route is v1.2.28.
This is index.html:
<html ng-app="myApp">
<head>
<script src="js/angulark.min.js"></script>
<script src="js/angular-routek.js"></script>
<script>
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'MainController',
templateUrl: 'views/nameView.html';
})
.when('/cityView',
{
controller: 'MainController',
templateUrl: 'views/cityView.html';
})
.otherwise({ redirectTo: '/' });
});
myApp.controller('MainController', ['$scope', function($scope) {
$scope.customers = [
{ name: 'Andre Queiroz', city: 'Rio de Janeiro' },
{ name: 'Fulano', city: 'Sao Paulo'},
{ name: 'Beltrano', city: 'Curitiba' }
];
$scope.addCustomer() = function () {
$scope.customers.push(
{ name: $scope.newCustomer.name, city: $scope.newCustomer.city }
);
};
}]);
</script>
<title>Meu Aplicativo</title>
</head>
<body>
<div>
<!-- Placeholder for views -->
<div ng-view> </div>
</div>
</body>
</html>
This is nameView.html
<div class="container">
<div ng-controller="MainController">
<div>
<h2>View 1</h2>
Name: <input type="text" ng-model="filter.name"/>
</div>
<br />
<ul>
<li ng-repeat="cust in customers | filter:filter.name | orderBy:'city'">{{cust.name | uppercase}} - {{cust.city}}</li>
</ul>
</div
<div>
<p>Customer name:</p>
<input type="text" ng-model="newCustomer.name" />
<p>Customer city:</p>
<input type="text" ng-model="newCustomer.city" />
<button ng-click="addCustomer()">Add customer </button>
View 2
</div>
</div>
</div>
The cityView.html is the same but with no addCustomer stuff. I was dividing into module file and so on, but i put it in one file to see if it worked.
There is a mistake in index.html javascript.
Inside MainController change your code
$scope.addCustomer() = function () {
$scope.customers.push(
{ name: $scope.newCustomer.name, city: $scope.newCustomer.city }
);
};
to
$scope.addCustomer= function () {
$scope.customers.push(
{ name: $scope.newCustomer.name, city: $scope.newCustomer.city }
);
};
it should $scope.addCustomer= instead of $scope.addCustomer()=
You're actually doing well. Most of erros are syntax.
Error 1: Remove ; from templateUrl inside $routeProvider.when()
Eq. templateUrl: 'views/cityView.html'
Error 2: Can't have parentheses to create a method with this sintaxe
$scope: Eq. $scope.newfunction = function() {...}
<html ng-app="myApp">
<head>
<script src="js/angulark.min.js"></script>
<script src="js/angular-routek.js"></script>
<script>
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'MainController',
templateUrl: 'views/nameView.html'
})
.when('/cityView',
{
controller: 'MainController',
templateUrl: 'views/cityView.html'
})
.otherwise({ redirectTo: '/' });
});
myApp.controller('MainController', ['$scope', function($scope) {
$scope.customers = [
{ name: 'Andre Queiroz', city: 'Rio de Janeiro' },
{ name: 'Fulano', city: 'Sao Paulo'},
{ name: 'Beltrano', city: 'Curitiba' }
];
$scope.addCustomer = function () {
$scope.customers.push(
{ name: $scope.newCustomer.name, city: $scope.newCustomer.city }
);
};
}]);
</script>
<title>Meu Aplicativo</title>
</head>
<body>
<div>
<!-- Placeholder for views -->
<div ng-view> </div>
</div>
</body>
</html>
There're some HTML errors in your view. Make sure to validate your HTML.
Error: In the line 11, you must fix from </div to </div>
Also, you don't need to add a controller. You already added on your config:
Remove it from your view: From <div
ng-controller="MainController"> to <div>
Not required, but best practice
On your last line, there's a spare </div>, get rid of it:
<div class="container">
<div ng-controller="MainController">
<div>
<h2>View 1</h2>
Name: <input type="text" ng-model="filter.name"/>
</div>
<br />
<ul>
<li ng-repeat="cust in customers | filter:filter.name | orderBy:'city'">{{cust.name | uppercase}} - {{cust.city}}</li>
</ul>
</div>
<div>
<p>Customer name:</p>
<input type="text" ng-model="newCustomer.name" />
<p>Customer city:</p>
<input type="text" ng-model="newCustomer.city" />
<button ng-click="addCustomer()">Add customer </button>
View 2
</div>
</div>
PS: Make sure you check your syntax errors. Using jshint, jslint or even Chrome dev tools / Firebug will help with that. You can set your editor(Sublimelinter for Sublime for example) to use jshint. Or use a IDE like Webstorm which comes with.
Related
In my current project I need to create a dynamic form using AngularJS.
I am already building the form following the ideas from this video here.
I can't seem to get the submitted data back to my controller. I only receive undefined in the console log.
Currently the data for the form is resolved in ui-router before the state is loaded, then copied to the controller's data property.
Unlike the video our form requires that questions are broken down into sections.
There is a ng-repeat over each section in the data, then a nested ng-repeat goes over each question. The type is determined and the proper directive for the question/field type is loaded to via ng-switch.
I whipped up a small Plunker to help illustrate as well.
https://plnkr.co/edit/6dCnHiFDEYu03kfX07mr
Finally there are some types I am unsure how to handle, such as address or phone number which will be considered one question type but have multiple fields.
(e.g. [Street] [City] [State] [Zip])
Controller
namespace portal.dashboard.form{
class formCtrl{
formData: portal.domain.interfaces.IHousingRequest;
static $inject = ["formResolve"];
constructor(private formResolve:any) {
this.formData= this.loadHousingRequestFormData;
}
public submit(isValid,data) {
if (isValid) {
console.log(data);
}
}
}
angular
.module("portal")
.controller("formCtrl", formCtrl);
}
Directive for input type text
namespace portal.directives {
function inputText(): ng.IDirective {
return {
scope: {
model: '='
},
controller: function ($scope: ng.IScope) {
var directiveScope = $scope.$parent.$parent;
},
controllerAs:'vm',
templateUrl: 'form/templates/input-text.html'
}
}
angular
.module("portal")
.directive("inputText", inputText);
}
input type html
<input type="text"
ng-model="model"/>
HTML
<form name="form" ng-submit="vm.submit(form.$valid, data)" novalidate>
<!-- Section repeat -->
<div ng-repeat="section in vm.formData.sections track by $index">
<section>
<div>
<h4>
{{section.name}}<br />
<small ng-show="section.description">{{section.description}}</small>
</h4>
</div>
<section>
<!-- Section questions repeat -->
<div ng-form="formFields" ng-repeat="field in section.fields track by $index">
<label>
{{field.name}}<br />
<small>{{field.description}}</small>
</label>
<!-- input field switch -->
<div ng-switch="field.type">
<div ng-switch-when="Text">
<input-text model="data.answer[$index]">
</input-text>
</div>
<div ng-switch-when="Email">
<input-email model="data.answer[$index]">
</input-email>
</div>
</div>
</div>
</section>
</section>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
You have to init $scope.data = {}; before using it, also use correct sectionIndex and fieldIndex to populate the answer:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.data = {};
$scope.sections = [{
name: 'User Info',
description: 'I\'m a description.',
fields: [{
label: "Name",
type: "text"
}, {
label: "Email",
type: "email"
}]
}, {
name: 'Pet Info',
description: '',
fields: [{
label: "Pet Breed",
type: "text"
}]
}];
$scope.submit = function(isValid, data) {
console.log('submit fired');
if (isValid) {
console.log(data);
}
}
});
app.directive('inputText', function() {
return {
scope: {
model: '='
},
controller: function($scope) {
var directiveScope = $scope.$parent.$parent;
},
controllerAs: 'vm',
template: '<input type="text" ng-model="model"/>'
}
});
app.directive('inputEmail', function() {
return {
scope: {
model: '='
},
controller: function($scope) {
var directiveScope = $scope.$parent.$parent;
},
controllerAs: 'vm',
template: '<input type="email" ng-model="model"/>'
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<body ng-app="plunker" ng-controller="MainCtrl">
<form name="form" ng-submit="submit(form.$valid, data)" novalidate>
<!-- Section repeat -->
<div ng-repeat="(sectionIndex, section) in sections track by $index">
<section>
<div>
<h4>
{{section.name}}<br />
<small ng-show="section.description">{{section.description}}</small>
</h4>
</div>
<section>
<!-- Section questions repeat -->
<div ng-form="formFields" ng-repeat="(fieldIndex, field) in section.fields track by $index">
<label>
{{field.label}}<br />
</label>
<!-- input field switch -->
<div ng-switch="field.type">
<div ng-switch-when="text">
<input-text model="data.answer[sectionIndex][fieldIndex]">
</input-text>
</div>
<div ng-switch-when="email">
<input-email model="data.answer[sectionIndex][fieldIndex]">
</input-email>
</div>
</div>
</div>
</section>
</section>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
</body>
Also I'm not sure why do you need this var directiveScope = $scope.$parent.$parent; in your directive's controller, do you really need this?
Trying to learn Angular/Rails basics, and I am on this page of this AngularJS web-app tutorial: https://thinkster.io/tutorials/angular-rails/creating-the-single-post-view
I'm encountering a problem I have spent countless hours pouring over, but since my JavaScript knowledge is limited and my Angular experience is none, I'm coming to the conclusion that I will never figure out what I've done wrong.
My main view/controller works fine, but when I click the Comments on a post, it can never pull the data correctly. You can see a demo of it not working here: http://joshmccord.com/demo/webapp/#/home - just click Comments and see it broken.
Here's the code for app.js:
angular.module('flapperNews', ['ui.router'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
// Make sure only last state has ending semicolon
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl'
})
.state('posts', {
url: '/posts/{id}',
templateUrl: '/posts.html',
controller: 'PostsCtrl'
});
$urlRouterProvider.otherwise('home');
}
])
.factory('posts', [function() {
// Service Body
var o = {
posts: []
};
return o;
// End Service Body
}])
// Make sure only last controller has ending semicolon
.controller('MainCtrl', [
'$scope',
'posts',
function($scope, posts){
// Bind $scope.posts to factory/services posts
$scope.posts = posts.posts;
$scope.posts = [
{title: 'Post 1', upvotes: 5},
{title: 'Post 2', upvotes: 2},
{title: 'Post 3', upvotes: 15},
{title: 'Post 4', upvotes: 9},
{title: 'Post 5', upvotes: 4}
];
$scope.addPost = function(){
if(!$scope.title || $scope.title === '') { return; }
$scope.posts.push({
title: $scope.title,
link: $scope.link,
upvotes: 0,
comments: [
{author: 'Joe', body: 'Cool post!', upvotes: 0},
{author: 'Bob', body: 'Great idea but everything is wrong!', upvotes: 0}
]
});
$scope.title = '';
$scope.link = '';
};
$scope.incrementUpvotes = function(post) {
post.upvotes += 1;
};
}])
.controller('PostsCtrl', [
'$scope',
'$stateParams',
'posts',
function($scope, $stateParams, posts){
$scope.post = posts.posts[$stateParams.id];
$scope.addComment = function(){
if($scope.body === '') { return; }
$scope.post.comments.push({
body: $scope.body,
author: 'user',
upvotes: 0
});
$scope.body = '';
};
}]);
And finally here is the index.html:
<html>
<head>
<title>My Angular App!</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css">
<link rel="stylesheet" href="app.css">
<script src="https://use.fontawesome.com/e1c22672d7.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.4.2/angular-ui-router.js"></script> <!-- http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js -->
<script src="app.js"></script>
</head>
<body ng-app="flapperNews">
<div class="top-bar">
<div class="top-bar-left">
<ul class="dropdown menu" data-dropdown-menu>
<li class="menu-text">Flapper News</li>
</ul>
</div>
<div class="top-bar-right">
<ul class="menu">
<li>Home</li>
<li><input type="search" placeholder="Search"></li>
<li><button type="button" class="button">Search</button></li>
</ul>
</div>
</div>
<div class="row mainView">
<div class="medium-6 medium-offset-3 columns">
<ui-view/>
</div>
</div>
<script type="text/ng-template" id="/home.html">
<div ng-repeat="post in posts | orderBy: '-upvotes'" class="postList">
<span class="fa fa-thumbs-up" ng-click="incrementUpvotes(post)"></span>
<a ng-show="post.link" href="{{post.link}}">
{{post.title}}
</a>
<span ng-hide="post.link">
{{post.title}}
</span>
<span>
Comments
</span>
- Upvotes: {{post.upvotes}}
</div>
<form ng-submit="addPost()" class="addPost">
<h4>Add A Post</h4>
<input type="text" placeholder="Title" ng-model="title">
<input type="text" placeholder="Link" ng-model="link">
<button type="submit" class="button expanded">Post</button>
</form>
</script>
<script type="text/ng-template" id="/posts.html">
<h3>
<a ng-show="post.link" href="{{post.link}}">
{{post.title}}
</a>
<span ng-hide="post.link">
{{post.title}}
</span>
</h3>
<div ng-repeat="comment in posts.comments | orderBy:'-upvotes'">
<span class="fa fa-thumbs-up" ng-click="incrementalUpvotes(comment)"></span>
{{comment.upvotes}} - by {{coment.author}}
<span style="font-size: 20px; margin-left: 10px;">
{{comment.body}}
</span>
</div>
<form ng-submit="addComment()" class="addComment">
<h4>Add A Comment</h4>
<input type="text" placeholder="Comment" ng-model="body">
<button type="submit" class="button expanded">Post</button>
</form>
</script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/js/foundation.min.js"></script>
</body>
</html>
I am new to AngularJS, Somehow while going through many sites now I am able to create a directive for showing some data.Now I need to send some data to controller by clicking the button. I need to know the proper way of doing this
I have created the plunk
html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="jquery#*" data-semver="2.2.0" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="movieDesc">
<div ng-repeat="m in movies" movies="m"></div>
</body>
</html>
Directive and Controller
// Code goes here
angular.module('app', []);
angular.module('app').controller('movieDesc', function($scope) {
$scope.movies = [{
name: 'abc',
desc: 'this is desc text for the movie',
pic: 'http://png.clipart.me/graphics/thumbs/134/abstract-geometric-background-triangle-and-square-black_134053397.jpg'
}, {
name: 'def',
desc: 'this is desc text for the movie def',
pic: 'http://png.clipart.me/graphics/thumbs/201/abstract-modern-banner-background-of-geometric-shapes-abstract-geometric-form_201768245.jpg'
}, {
name: 'ghi',
desc: 'this is desc text for the movie ghi',
pic: 'http://www.cianellistudios.com/images/abstract-art/abstract-art-infinite-150.jpg'
}]
$scope.saveData = function(data) {
console.log(data);
}
});
angular.module('app').directive('movies', function() {
return {
templateUrl: "movieCard.html",
restrict: "EA",
scope: {
movies: '='
},
link: function(scope, element, attrs) {
element.addClass('moviesBox');
var clickedFn = function() {
alert("clicked");
};
console.log("console", element[0].querySelector('.btnSelect'));
var $this = element[0].querySelector('.btnSelect');
$($this).click(function() {
alert(scope.movies.desc)
})
}
}
})
My Template
<div>
<div>
<b>Name:</b> {{movies.name}}
</div>
<div>
<b>Description:</b> {{movies.desc}}
</div>
<div>
<img src="{{movies.pic}}" />
</div>
<div>
<input type="text" ng-model="movies.someText">
</div>
<div>
<input class="btnSelect" type="button" value="Desc" ng-click="clickedFn()">
</div>
<div>
<input class="btnSelect" type="button" value="Save Data" ng-click="saveData({{movies}})">
</div>
</div>
I need to send the data to the controller's $scope.saveData() function, the data will be entered through the textbox. I have given it as ng-model="movies.someText" which I suppose is the wrong way.
So please help me.
Use the & scope binding.
scope: {
movies: '=',
save: '&'
},
and in the directive template
<input type="button" ng-click="save({movie: movies})" ...>
You then bind the controller method via
<div ng-repeat="m in movies" movies="m" save="saveData(movie)"></div>
Note the argument name passed to the controller function matches the object key in the directive template.
https://plnkr.co/edit/9bF5FDea6wLn7vcGvEzU?p=preview
While you're there, use ng-src instead of src to avoid a 404 request for a non-existent image
<img ng-src="{{movies.pic}}" />
html
<body ng-controller="movieDesc">
<div ng-repeat="m in movies" movies="m">
<movies-dir
movies="m" save-data="saveData(movie)"></movies-dir>
</div>
</body>
Directive and Controller
angular.module('app', []);
angular.module('app')
.controller('movieDesc', function($scope) {
$scope.movies = [/* movie object array data */]
$scope.saveData = function(movie) {
console.log(movie);
}
});
angular.module('app').directive('moviesDir', function() {
return {
templateUrl: "movieCard.html",
restrict: "EA",
scope: {
movies: '=',
saveData: '&'
},
link: function(scope, element, attrs) {
}
}
})
Template
<div>
<input class="btnSelect" type="button" value="Save Data" ng-click="saveData({ 'movie': movies })">
</div>
You need to pass saveData as a parameter like this:
<body ng-controller="movieDesc">
<div ng-repeat="m in movies" movies="m" save-data="saveData()"></div>
And you get back in your directive like this:
return {
templateUrl: "movieCard.html",
restrict: "EA",
scope: {
movies: '=',
saveData:'='
},
link: ...
And then in your template.html, you don't need to use '{{}}' :
<input class="btnSelect" type="button" value="Save Data" ng-click="saveData(movies)">
My custom background image is not showing up in AngularJS. Can't figure out why.
When I test $scope.setBackground in console, I get Object {background-image: "url(image.jpg)"}
Controller:
app.controller('backgroundImageCtrl', function($scope, $http) {
$scope.setBackground = {
'background-image' : 'url(image.jpg)'
};
})
HTML:
<script type = "text/ng-template" id="/page.html" ng-controller="backgroundImageCtrl" ng-style="setBackground">
<div>
...
</div>
</script>
var app = angular.module('myApp', []);
app.controller("myCtrl", function ($scope) {
$scope.style= {};
$scope.setBackground = function (date) {
$scope.style = {
'background-image': 'url("https://www.gravatar.com/avatar/10821c595d354140ee66f2a04fb11b7c?s=32&d=identicon&r=PG&f=1")'
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<button ng-click="setBackground()">set background</button>
<div ng-style="style">see the background</div>
</div>
</div>
Simple solution as suggested by #Mosh Feu, simply place ng-controller="backgroundImageCtrl" and ng-style="setBackground" in an inner div
<script type = "text/ng-template" id="/page.html">
<div ng-controller="backgroundImageCtrl" ng-style="setBackground">
...
</div>
</script>
you should use setBackground in div that use your template. try like this.
<div ng-include src="/page.html" ng-style="setBackground"></div>
var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/addStudent', {
templateUrl: 'addStudent.htm',
controller: 'AddStudentController'
}).
when('/viewStudents', {
templateUrl: 'viewStudents.htm',
controller: 'ViewStudentsController'
}).
otherwise({
redirectTo: '/addStudent'
});
}]);
mainApp.controller('AddStudentController', function($scope) {
$scope.message = "This page will be used to display add student form";
$scope.setBackground = {
'background-image' : 'url(https://www.gravatar.com/avatar/10821c595d354140ee66f2a04fb11b7c?s=32&d=identicon&r=PG&f=1)'
};
});
mainApp.controller('ViewStudentsController', function($scope) {
$scope.message = "This page will be used to display all the students";
$scope.setBackground = {
'background-image' : 'url(https://www.gravatar.com/avatar/6755dcaf172d19cb9976bedcc56cfed3?s=48&d=identicon&r=PG&f=1)'
};
});
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js"></script>
<div ng-app = "mainApp">
<p>Add Student</p>
<p>View Students</p>
<div ng-view ng-style="setBackground"></div>
<script type="text/ng-template" id="addStudent.htm">
<h2> Add Student </h2>
{{message}}
</script>
<script type = "text/ng-template" id="viewStudents.htm">
<h2> View Students </h2>
{{message}}
</script>
</div>
I was working on developing a comment page based on https://thinkster.io/mean-stack-tutorial. But the page does not appear at all. Here is the code:
In index.ejs in views directory:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<script src="/javascripts/ang.js"></script>
</head>
<body ng-app="peopleComments">
<script type="text/ng-template" id="/home.html">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="page-header">
<h2>Learn. Share. Popularize.</h2>
</div>
<p>Share here to let the world know.</p>
<hr/>
<div ng-repeat="comment in comments|orderBy:'-upvotes'" style="line-height:25px">
{{comment.username}} - {{comment.contents}}
<br>
{{comment.upvotes}}
<span class="glyphicon glyphicon-triangle-top" ng-click="increaseUpvotes(comment)" style="color:green"></span>
{{comment.downvotes}}
<span class="glyphicon glyphicon-triangle-bottom" ng-click="increaseDownvotes(comment)" style="color:red"></span>
<hr/>
</div>
<form ng-submit="addComment()">
<div class="col-xs-2">
<div class="form-group">
<input type="text" class="form-control" placeholder="Your Name" ng-model="username"></input>
</div>
</div>
<div class="col-xs-8">
<div class="form-group">
<input type="text" class="form-control" placeholder="What would you like to share?" ng-model="contents"></input>
</div>
</div>
<button class="btn btn-info" type="submit">Add My Entry</button>
</form>
</div>
</div>
</div>
</script>
</body>
</html>
In comments.js in models directory:
var mongoose = require('mongoose');
var CommentSchema = new mongoose.Schema({
username: String,
contents: String,
upvotes: {type: Number, default: 0},
downvotes:{type:Number, default:0}
});
CommentSchema.methods.upvote=function(cb){
this.upvotes+=1;
this.save(cb);
};
mongoose.model('Comment', CommentSchema);
In ang.js in public/javascripts directory:
var app=angular.module('peopleComments',['ui.router']);
app.factory('comments',['$http', function($http){
var c={
comments:[]
};
//loading all existing comments with getAll()
c.getAll=function(){
return $http.get('/comments').success(function(data){
angular.copy(data, c.comments);
});
};
//function which creates the new comments for updating in the database
c.create = function(comment) {
return $http.post('/comments', comment).success(function(data){
c.comments.push(data);
});
};
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
//setting up a home state
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'Base',
resolve: {
comment: ['comments', function(comments){ //using resolve property of ui-router - not rendering???
return comments.getAll();
}]
}
});
$urlRouterProvider.otherwise('home');
}]);
app.controller('Base',[
'$scope','comments',function($scope,comments){
$scope.addComment=function(){ //add new comments to the server/display existing ones
$scope.comments=comments.comments;
if(!$scope.username||$scope.username=='') {$scope.username='Anonymous';}
if(!$scope.contents||$scope.contents==''){return;}
comments.create({
username: $scope.username,
contents: $scope.contents,
}); $scope.comments.push({username:$scope.username,contents:$scope.contents,upvotes:0,downvotes:0});
$scope.username='';
$scope.contents='';
}
$scope.comments = [
{username: 'Diana', contents:'In either a quantum world or in a higher dimension, the past, present and future co-exist!', upvotes: 5, downvotes:0},
{username: 'Cindy', contents:'Never wash strawberries or any berry unless you intend to eat them right away or they will mold.', upvotes: 7, downvotes:0}
];
}]);
The comments given above should appear.. But they aren't.. Why??
I think your problem is that you've created a template, but you're not using the template.
I'm not 100% sure you need a template but try:
<div ng-include src="home.html"></div>
See this example of switching templates dynamically JSFiddle
It looks like the Controller will not wait for comment to load because it doesn't depend on it. Making the controller depend on the comment promise as well as the comments service should make the dependency clear to Angular.
app.controller('Base',[
'$scope','comments', 'comment', function($scope,comments,_comment){
// ...
}]);
The mistake was that I had to add
<ui-view></ui-view>
where I needed my template to load as per the ui-router syntax.