AngularJS insert data to to JSON file - angularjs

I have been trying and failing at this all day. I'm quite new to all this. This is a very simple angularJS learning exercise that I can't figure out.
My GET command successfully pulls the JSON data but the POST command in the addItem function is non-responsive. I believe I'm missing the server configuration but I don't know where I would put this.
There are only two files; the app and the json file (list.php); the content of both below. This app is currently running at:
http://pagemakr.com/list/L8/
THE APP - index.php:
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrlx", function($scope,$http) {
$http.get("list.php").then(function (response) {
$scope.items = response.data.items;
});
$scope.addItem = function () {
var data = { "item":$scope.itemInput }
$http.post("list.php", data).then(function (response) {
if (response.data)
$scope.msg = "Success!";
}, function (response) {
$scope.msg = "Didn't Work!";
});
}
});
</script>
<div ng-app="myShoppingList" ng-cloak ng-controller="myCtrlx" class="w3-card-2 w3-margin" style="max-width:400px;">
<header class="w3-container w3-light-grey w3-padding-16"><h3>List</h3></header>
<ul class="w3-ul">
<li ng-repeat="x in items" class="w3-padding-16">{{x.item}}<span ng-click="removeItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">x</span></li>
</ul>
<div class="w3-container w3-light-grey w3-padding-16">
<div class="w3-row w3-margin-top">
<div class="w3-col s10">
<input placeholder="Add items here" ng-model="itemInput" class="w3-input w3-border w3-padding">
</div>
<div class="w3-col s2">
<button type="button" value="Submit" ng-click="addItem()" class="w3-btn w3-padding w3-green">Add</button>
</div>
</div>
<p class="w3-text-red">{{errortext}}</p>
</div>
</div>
THE JSON DATABASE - list.php:
{
"items":
[
{"item":"peas"},
{"item":"carrots"},
{"item":"jam"}
]
}

Related

Update view when api get data in Angularjs

So, i have a little problem. I made a tiny webapp that uses the omdb api. The thing is this that when i type in the movie that i'm searching for then press the search button, the view should change to the result.html view and show the data i got from the api.
The api works fine. I got the data to display, but that was in my index.html. Now i have splitted the files by using ng-routes
I can provide you the whole project if you wanna look at it. Maybe i can upload it to a online editor somewhere?
This is my app.js
var myApp = angular.module("myApp", ['ngRoute']);
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'views/home.html',
controller: 'filmController'
}).
when('/result', {
templateUrl: 'views/result.html',
controller: 'filmController'
}).otherwise({
redirectTo: '/home'
})
}]);
myApp.controller("filmController", function filmController($scope, $http, $window) {
$scope.getData = function () {
var movieTitle = document.getElementById("filmName").value;
var binding = document.getElementsByClassName("ng-binding");
$http
.get("http://www.omdbapi.com/?t=" + movieTitle + "&apikey=526345a6")
.then(function (response) {
var data = response.data;
if (data.Error) {
alert("Film inte funnen");
return false;
}
for (let key in data) {
if (data.hasOwnProperty(key)) {
let element = data[key];
if (element === "N/A") {
data[key] = "Inget hittat";
if (key === "Poster") {
$scope.post = "Ingen poster hittad";
}
}
$scope.url = data;
}
}
if (data.Ratings.length === 0) {
$scope.rate = "Ingen utmärkelse/er hittad";
}
// This api data is printed to the console on the index.html view, i want it in the result view...
console.log(data);
});
};
});
This is my index.html
<body>
<div class="main-content">
<!-- <div class="container">
<div class="row">
<div ng-controller="MyController">
<div ng-repeat="item in larare" class="col-lg-12">
<div class="card">
<img ng-src="/images/{{item.shortname}}.jpg" alt="Bild på {{item.name}}" class="card-img-top">
<div class="card-body">
<h3 class="card-title">{{item.name}}</h3>
<p class="card-text">{{item.reknown}}</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div> -->
<header ng-include="'header.html'"></header>
<main ng-view></main>
</div>
</div>
<script>
var elem = document.getElementsByTagName("body")[0];
if (elem.requestFullscreen) {
elem.requestFullscreen();
console.log("Nu");
} else {
console.log("Error");
}
function updateSite(event) {
window.applicationCache.swapCache();
}
window.applicationCache.addEventListener('updateready',
updateSite, false);
</script>
<script src="./js/formvalidation.js"></script>
</body>
</htm>
And my result view
<div class="show container" ng-show="url.Title">
<div class="poster">
<!-- <img ng-src="{{ url.Poster }}" alt="" /> -->
<img ng-src="{{ url.Poster == 'Inget hittat' ? './images/image_not_found.png' : url.Poster }}">
<p class="text-dark">{{ post }}</p>
</div>
<h2 class="text-dark">{{ url.Title | uppercase}}</h2>
<div class="movie-info">
<p class="text-dark">
<strong>Från:</strong> {{ url.Year }}</p>
<p class="text-dark">
<strong>Rating:</strong> {{ url.Rated }}</p>
<p class="text-dark">
<strong>Utgiven:</strong> {{ url.Released }}</p>
<p class="text-dark">
<strong>Längd:</strong> {{ url.Runtime }}</p>
</div>
<p class="text-dark">
<strong>Skådespelare:</strong> {{ url.Actors }}</p>
<p class="text-dark">
<strong>Regissör:</strong> {{ url.Director }}</p>
<p class="text-dark">
<strong>Utmärkelser:</strong> {{ url.Awards }}</p>
<p class="text-dark">
<strong>Handling: </strong> {{ url.Plot }}</p>
<h4 class="text-dark">
<strong>Utmärkelser</strong>
</h4>
<p class="text-dark ">{{ rate }}</p>
<div ng-repeat="rating in url.Ratings | orderBy: '-Value'">
<p class="text-dark">
<strong>{{ rating.Source + ': ' + rating.Value }}</strong>
</p>
</div>
This is my home view
<section class="text-white">
<img src="./images/background.jpg" alt="Bild på poster från Frankenstein filmen" class="bg-image">
<div class="main container align-middle">
<div class="row text-center justify-content-center section-intro">
<div class="col-6 mb-5">
<h1>Filmtipset</h1>
<h5>Sök efter dina favortfilmer</h5>
</div>
</div>
<form ng-submit="getData()">
<div class="inputSearch mx-auto">
<div class="row justify-content-center">
<div class="col-8">
<div class="form-group">
<label for="filmName">Film</label>
<input class="form-control" type="text" name="filmName" id="filmName" placeholder="Ex. Armageddon" autofocus>
</div>
<input type="submit" class="btn btn-primary btn-lg btn-block btn-info mt-5" onclick="validateForm()" ng-click="'#!/result'">
</div>
</div>
</form>
Just a few notes before we break down the issue you are seeing. It seems like you aren't using angularjs to its full potential. Using a mixture of jquery and angularjs is not best practice and can make debugging very difficult. I would recommend making movieTitle an ng-model, as well as using angularjs's built in form validation. This will allow you to access the movieTitle easily in your controller as well as take advantage of angular's built in form controller and actions.
As for getting the data to your other page, I would add a second controller for that page, then from your filmController, you can pass the movie title as a route param when changing views. In your resultController, you can get the movie title from the route param and then do your api call while initializing the result page/controller.
In your home.html file, we will add ng-model to the input to be more angularjs friendly. Now we can access movieTitle in the controller with $scope.movieTitle. I am also changing the method that should get run on submit to the search() method I have added to the filmController.
home.html
<form ng-submit="search()">
// ... your other html here
<input class="form-control" type="text" name="filmName" id="filmName" ng-model="movieTitle" placeholder="Ex. Armageddon" autofocus>
In your filmController, I would add $location and move the getData() method to a resultController. We will now call search() on form submit, then use $location to switch views to your result view, attaching the movie title as a route param so we can access it in the resultController.
filmController.js
myApp.controller("filmController", function filmController($scope, $http, $location) {
// ... other code you have
// this will be what gets called after the user types a movie title
$scope.search = function () {
var title = $scope.movieTitle; // or using jquery(not recommended)
// this will change location and will produce
// the url: http://[yoursite]/result?movieTitle=title
$location.path('/result').search({movieTitle: title});
}
});
In your newly created resultController, we will get that route param and use it to search for the data.
resultController.js
myApp.controller("resultController", function resultController($scope, $http, $routeParams) {
// the getData method moved to this controller
$scope.getData = function (movieTitle) {
$http
.get("http://www.omdbapi.com/?t=" + movieTitle + "&apikey=526345a6")
// the rest of your code for getData here
};
// I like to make an init method to make it clear what we are initializing
$scope.init = function () {
// this will get the movieTitle from the /result?movieTitle=title part of your url
var movieTitle = $routeParams['movieTitle'];
// now we call the method you have that uses the omdb api
// just modify it to accept the movie title as a param rather than finding it in the html
$scope.getData(movieTitle);
}
// run init method
$scope.init();
});
Finally, you will want to update your app config to have your result route use the resultController we added instead of the filmController.

Controller doesn't get parent data

I'm doing a tutorial over angular 1.5 and I've gotten far into it and one of the sections seems broken concerning matching a current user to the author username. The class injects the User service and I think assumes I can inherit from a parent controller for the author but it comes up undefined. I tried injecting $scope then setting a variable to $scope.$parent.article (article is the object that has the author name in it) but this was still undefined. I checked the parent controller doing a console log on article and it does have the data that I am trying to get. Here is a link to my project if you want to look at the entire thing but I'll try to post just the relevant code below. https://github.com/RawleJuglal/flow_news_app/tree/front_end/src/js
Parent Controller (article.controller.js)
import marked from 'marked';
class ArticleCtrl {
constructor(article, $sce, $rootScope) {
'ngInject';
this.article = article;
console.log(this.article);
//THIS IS CONSOLE LOG
//{title: "Juglal For StackOverflow",
slug: "juglal-for-stackoverflow-ba400n",
body: "<p> Need the goods</p>",
createdAt: "2017-04-25T14:51:42.131Z",
updatedAt: "2017-04-25T14:51:42.131Z",
author:{
bio:"I'm a MEAN stack developer. But if I don't find a job in Oklahoma soon, I'll be learning C++/Sharp."
following:false
image:"https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/6/000/1e9/0e2/3cd7175.jpg"
username:"RawleJuglal",....
}
// Update the title of this page
$rootScope.setPageTitle(this.article.title);
this.article.body = $sce.trustAsHtml(marked(this.article.body, { sanitize: true }));
}
}
export default ArticleCtrl;
Child Controller (article-actions.components.js)
class ArticleActionsCtrl {
constructor(Articles, User, $state) {
'ngInject';
this._Articles = Articles;
this._$state = $state;
//Code that causes the error because this.article.author.username is undefined
if (User.current) {
this.canModify = (User.current.username === this.article.author.username);
} else {
this.canModify = false;
}
}
}
let ArticleActions = {
bindings: {
article: '='
},
controller: ArticleActionsCtrl,
templateUrl: 'article/article-actions.html'
};
export default ArticleActions;
HTML(article.html) //Just in case this the problem
<div class="article-page">
<div class="banner">
<div class="container">
<h1 ng-bind="::$ctrl.article.title"></h1>
<article-actions article="$ctrl.article"></article-actions>
</div>
</div>
<div class="container page">
<div class="row article-content">
<div class="col-xs-12">
<div>
<div ng-bind-html="::$ctrl.article.body"></div>
</div>
<ul class="tag-list">
<li class="tag-default tag-pill tag-outline"
ng-repeat="tag in ::$ctrl.article.tagList">
{{ tag }}
</li>
</ul>
</div>
</div>
<hr />
<div class="article-actions">
<article-actions article="$ctrl.article"></article-actions>
</div>
<div class="row">
<div class="col-xs-12 col-md-8 offset-md-2">
<div>
<form class="card comment-form">
<div class="card-block">
<textarea class="form-control"
placeholder="Write a comment..."
rows="3"></textarea>
</div>
<div class="card-footer">
<img class="comment-author-img" />
<button class="btn btn-sm btn-primary" type="submit">
Post Comment
</button>
</div>
</form>
</div>
<div class="card">
<div class="card-block">
<p class="card-text">This is an example comment.</p>
</div>
<div class="card-footer">
<a class="comment-author" href="">
<img class="comment-author-img" />
</a>
<a class="comment-author" href="">
BradGreen
</a>
<span class="date-posted">
Jan 20, 2016
</span>
</div>
</div>
</div>
</div>
</div>
</div>
In fact, your example will work with angular 1.5 but not >1.6.
here is the reason :
Starting with angular 1.6, bindings are not yet set in the constructor. If you need them, move your code to the $onInit function.
Here is your new ArticleActionsCtrl :
class ArticleActionsCtrl {
constructor(Articles, User, $state) {
'ngInject';
this._Articles = Articles;
this._$state = $state;
this.User = User;
}
$onInit() {
if (this.User.current) {
this.canModify = (this.User.current.username === this.article.author.username);
} else {
this.canModify = false;
}
}
}
let ArticleActions = {
bindings: {
article: '='
},
controller: ArticleActionsCtrl,
templateUrl: 'article/article-actions.html'
};
export default ArticleActions;
I did not test it, do not hesitate to tell me if you have any problem with it.

MEAN stack editing a post

So I am working on my very first MEAN stack app and I am using using type script.
I have my post working just fine, but my edit post is not working. Since this is my first app I am not quite sure why. The error says that my parameters for my post are undefined. I hope one of you lovely people can help me out. I've avoided asking for help for a long time because I am sure its a stupid error.
controllers.ts
http://pastebin.com/bhXT5bLz
app.ts
state('jobPost', {
url: '/jobPost',
templateUrl: "/templates/jobPost.html",
controller: MyApp.Controllers.jobPostController,
controllerAs: 'jobPost'
})
.state('editjobPost', {
url: '/editjobPost',
templateUrl: "/templates/jobPost.html",
controller: MyApp.Controllers.jobPostController,
controllerAs: 'jobPost'
})
route.ts:
router.get('/jobPostData', function (req, res) {
console.log('getting jobPost data');
JobPost.find({}, function(err, jobposts) {
res.json(jobposts);
});
});
router.put('/jobPost', function (req, res, next) {
console.log('editing jobPost');
let jobPost = new JobPost({
jobTitle: req.body.jobTitle,
jobLocation: req.body.jobLocation,
jobDescription: req.body.jobDescription,
created_at: req.body.created_at
});
console.log(jobPost);
jobPost.save(function(err, jobPost) {
if (err) return next(err);
console.log('edited post');
res.send(jobPost);
});
});
jobPost.html:
<link rel="stylesheet" href="/css/jobPost.css" media="screen" title="no title" charset="utf-8">
<br><br><br><br><br><br><br>
<div class="container-fluid">
<div class="container">
<div class="row">
<div ng-show="jobPost.newForm" class="col-md-12" id="background">
<h1 class="headers">Post a Job</h1>
<form ng-submit="jobPost.newJobPost()" class="new_job_form" name="new_job_form">
<input ng-model="jobPost.jobPost.title" id="jobTitle" type="text" name="jobTitle" placeholder="job title"> <br><br>
<input ng-model="jobPost.jobPost.location" id="jobLocation" type="text" name="jobLocation" placeholder="job location"> <br><br>
<textarea ng-model="jobPost.jobPost.description" rows="8" cols="50"class="input-block-level" id="jobDescription" name="jobDescription" placeholder="Enter Description" ></textarea><br>
<input class="submit-btn" type="submit" name="submit" value="Submit">
</form>
<!-- <h2>{{jobPost.message}}</h2> -->
</div>
<div ng-show="jobPost.editForm" class="col-md-12" id="background">
<h1 class="headers">Edit a Job</h1>
<form ng-submit="jobPost.editJobPost()" class="edit_job_form" name="edit_job_form">
<input ng-model="jobPost.jobPost.title" type="text" name="jobTitle" value="{{editJobPost.editTitle}}"> <br><br>
<input ng-model="jobPost.jobPost.location" type="text" name="jobLocation" value="{{editJobPost.editLocation}}"> <br><br>
<textarea ng-model="jobPost.jobPost.description" rows="8" cols="50"class="input-block-level" name="jobDescription" value="{{editJobPost.editDescription}}" ></textarea><br>
<input class="submit-btn" type="submit" name="submit" value="Submit">
</form>
</div>
</div
</div>
</div>
</div>
<br><br>
<div class="container-fluid">
<div class="container">
<h1 class="headers">Your Jobs</h1>
<div class="row" ng-repeat="job in jobPost.jobPosts.slice(((jobPost.currentPage-1)*jobPost.itemsPerPage),((jobPost.currentPage)*jobPost.itemsPerPage)) | orderBy : 'created_at' ">
<h1></h1>
<div class="col-md-12 jobPosting panel-title">
<h2>{{job.jobTitle}}<a class="pull-right" ui-sref="editjobPost"><span ng-click="jobPost.editJobPost()" class="glyphicon glyphicon-cog"></a></h2>
<h3>{{job.jobLocation}}</h3>
<h3>{{job.jobDescription}}</h3>
</div>
</div>
<!-- <pagination total-items="jobPost.totalItems" ng-model="jobPost.currentPage" ng-change="jobPost.pageChanged()" class="pagination-sm" items-per-page="jobPost.itemsPerPage"></pagination> -->
<ul uib-pagination total-items="jobPost.totalItems" items-per-page="jobPost.itemsPerPage" ng-model="jobPost.currentPage" ng-change="jobPost.pageChanged()"></ul>
<!-- <ul uib-pagination total-items="totalItems" ng-model="JobPost" ng-change="pageChanged()"></ul> -->
<!-- <h4>Default</h4>
<h5>totalItems: {{jobPost.totalItems}}</h5>
<ul uib-pagination total-items="jobPost.totalItems" ng-model="jobPost.currentPage" ng-change="jobPost.pageChanged()"></ul> -->
<!-- <ul uib-pagination boundary-links="true" total-items="jobPost.totalItems" ng-model="jobPost.currentPage" class="pagination-sm" previous-text="‹" next-text="›" first-text="«" last-text="»"></ul>
<ul uib-pagination direction-links="false" boundary-links="true" total-items="jobPost.totalItems" ng-model="jobPost.currentPage"></ul>
<ul uib-pagination direction-links="false" total-items="jobPost.totalItems" ng-model="jobPost.currentPage" num-pages="smallnumPages"></ul>
<pre>The selected page no: {{jobPost.currentPage}}</pre>
<button type="button" class="btn btn-info" ng-click="jobPost.setPage(3)">Set current page to: 3</button> -->
<hr />
</div>
</div>
<script src="/js/jobForm.js" charset="utf-8"></script>
jobForm.ts:
$(document).ready(function() {
$('.new_job_form').on('submit', function(e){
e.preventDefault();
var jobTitle = $('#jobTitle').val();
var jobLocation = $('#jobLocation').val();
var jobDescription = $('#jobDescription').val();
$('#jobTitle').val('');
$('#jobLocation').val('');
$('#jobDescription').val('');
var data = {
jobTitle: jobTitle,
jobLocation: jobLocation,
jobDescription: jobDescription,
};
console.log(data);
$.ajax({
url: '/jobPost',
dataType: "json",
method: "POST",
data: data,
success: function(data, textStatus, jqXHR){
console.log("Successfully saved to database",data);
// var resultString = "<h4>"+data.jobTitle+"</h4><h4>"+data.jobLocation+"</h4><h4>"+data.jobDescription+"</h4>";
// $('.postResult').html(resultString);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});
angular.module('MyApp').controller('jobPostController', function ($scope, $log) {
$scope.totalItems = 64;
$scope.currentPage = 1;
$scope.setPage = function (pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function() {
$log.log('Page changed to: ' + $scope.currentPage);
};
$scope.maxSize = 5;
$scope.bigTotalItems = 175;
$scope.bigCurrentPage = 1;
});
});
****EDIT to reflect answering stack overflow checklist
I have tried messing with the ui-sref and ng-click for the editJobPost section in the JobPost.html thinking maybe it was a routing error.
I then changed the editJobPost method in controller.js from the JobPost variable to JobPosts variable. Now that it runs and compiles (it didn't before) it throws this in the console:
HITTING EDIT
controllers.js:241 undefined
controllers.js:242 undefined
controllers.js:245 undefined
controllers.js:249 Title: undefined
controllers.js:250 Location: undefined
controllers.js:251 Description: undefined
angular.js:11881 PUT http://127.0.0.1:3000/jobPost/%7B%7Bjob._id%7D%7D 404 (Not Found)
I know that it means my declared variables are undefined, I just don't know where to start. what is wrong and why.

Passing data from one page to another in angular js

How do I pass data from one page to another in angular js?
I have heard about using something as services but I am not sure how to use it!
Given below is the functionality I want to execute!
On page 1:
<div class="container" ng-controller="mycontrl">
<label for="singleSelect"> Select Date </label><br>
<select nAMe="singleSelect" ng-model="dateSelect">
<option value="2/01/2015">2nd Jan</option>
<option value="3/01/2015">3rd Jan</option>
</select>
<br>
Selected date = {{dateSelect}}
<br/><br/><br/>
<label for="singleSelect"> Select time </label><br>
<select nAMe="singleSelect" ng-model="timeSelect">
<option value="9/10">9AM-10AM</option>
<option value="10/11">10AM-11AM</option>
<option value="11/12">11AM-12PM</option>
<option value="12/13">12PM-1PM</option>
<option value="13/14">1PM-2PM</option>
</select>
<button ng-click="check()">Check!</button>
<br>
Selected Time = {{timeSelect}}
<br/><br/>
User selects time and date and that is used to make call to the db and results are stored in a variable array!
Page 1 controller:
var config= {
params: {
time: times,
date:dates
}
};
$http.get('/era',config).success(function(response) {
console.log("I got the data I requested");
$scope.therapist_list = response;
});
Now how do I send this variable $scope.therapist_list which is an array to next page which will be having a different controller and also if services is use how do define it in my application.js file
application.js:
var firstpage=angular.module('firstpage', []);
var secondpage=angular.module('secondpage', []);
To save the data that you want to transfer to another $scope or saved during the routing, you can use the services (Service). Since the service is a singleton, you can use it to store and share data.
Look at the example of jsfiddle.
var myApp = angular.module("myApp", []);
myApp.controller("ExampleOneController", function($scope, NewsService) {
$scope.news = NewsService.news;
});
myApp.controller("ExampleTwoController", function($scope,NewsService) {
$scope.news = NewsService.news;
});
myApp.service("NewsService", function() {
return {
news: [{theme:"This is one new"}, {theme:"This is two new"}, {theme:"This is three new"}]
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="ExampleOneController">
<h2>
ExampleOneController
</h2>
<div ng-repeat="n in news">
<textarea ng-model="n.theme"></textarea>
</div>
</div>
<div ng-controller="ExampleTwoController">
<h2>
ExampleTwoController
</h2>
<div ng-repeat="n in news">
<div>{{n.theme}}</div>
</div>
</div>
</body>
UPDATED
Showing using variable in different controller jsfiddle.
var myApp = angular.module("myApp", []);
myApp.controller("ExampleOneController", function($scope, NewsService) {
$scope.newVar = {
val: ""
};
NewsService.newVar = $scope.newVar;
$scope.news = NewsService.news;
});
myApp.controller("ExampleTwoController", function($scope, NewsService) {
$scope.anotherVar = NewsService.newVar;
$scope.news = NewsService.news;
});
myApp.service("NewsService", function() {
return {
news: [{
theme: "This is one new"
}, {
theme: "This is two new"
}, {
theme: "This is three new"
}]
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="ExampleOneController">
<h2>
ExampleOneController
</h2>
<div ng-repeat="n in news">
<textarea ng-model="n.theme"></textarea>
</div>
<input ng-model="newVar.val">
</div>
<div ng-controller="ExampleTwoController">
<h2>
ExampleTwoController
</h2>
<div ng-repeat="n in news">
<div>{{n.theme}}</div>
</div>
<pre>newVar from ExampleOneController {{anotherVar.val}}</pre>
</div>
</body>
OK,
you write a another module ewith factory service e.g.
angular
.module('dataApp')
.factory('dataService', factory);
factory.$inject = ['$http', '$rootScope', '$q', '$log'];
function factory($http, $rootScope,$q,$log) {
var service = {
list: getList
};
service.therapist_list = null;
return service;
function getList() {
var config= {
params: {
time: times,
date:dates
}
};
$http.get('/era',config).success(function(response) {
console.log("I got the data I requested");
$scope.therapist_list = response;
});
$log.debug("get Students service");
$http.get('/era',config).then(function successCallback(response) {
service.therapist_list = response.data;
$log.debug(response.data);
}, function errorCallback(response) {
$log.debug("error" + response);
});
}
}
Add this module as dependencies to your both page apps like
var firstpage=angular.module('firstpage', [dataApp]);
var secondpage=angular.module('secondpage', [dataApp]);
and then in your controller consume that service
.controller('homeController', ['$scope', 'dataService', function ($scope, dataService) {
}]);

Trouble getting Comment Form to POST - Angular App

I'm relatively new to Angular. I'm trying to get my comment form of this blog app to post comments and not just keep them in Javascript but via API POST to my database and store them there. I'm able to GET comments as well as other blog post information but for whatever reason I can't POST.
BlogService.js
angular.module('BlogService', [])
.factory('BlogService', ['$http', function($http) {
return {
// Call to GET Blog API
get : function() {
return $http.get('/api/blog');
},
// Call to GET Blog API via ID
show : function() {
return $http.get('/api/blog/' + id);
},
// Call to POST new data using Blog API
create : function(blogData) {
return $http.post('/api/blog', $scope.formData);
},
// Call to POST Comments in Blog API
createComment : function(commentData) {
return $http ({
method: 'POST',
url: '/api/blog/' + id + '/comments',
header: { 'content-type' : 'application/x-www-form-urlencode},
data: $.param(commentData)
});
},
// Call to PUT to update data using Blog API
update : function(id) {
return $http.put('/api/blog' + id);
},
// Call to DELETE data using Blog API
delete : function(id) {
return $http.delete('/api/blog/' + id);
}
}
}]);
CommentCtrl
To note, this CommentCtrl is a part of a larger BlogCtrl.js. I just separated it into its own controller. If it'll help, I can post the whole file.
...
.controller('CommentCtrl', ['$scope', '$http', 'BlogService', function($scope, $http, BlogService) {
this.commentData = {};
this.addComment = function(post) {
BlogService.createComment(this.commentData)
.success(function(data) {
this.commentData = {};
this.commentData.createdOn = Date.now();
post.comments.push(this.commentData);
this.commentData = {};
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}]);
blog.html
The form is the part that I'm trying to POST. This is just a snippet of the markdown. Let me know if you would like to see the whole html file.
<div class="post" ng-repeat="post in blog.posts" ng-show="blog.isSelected($index)">
<div>
<h2>{{post.title}}</h2>
<img ng-src="{{post.image}}" ng-show="{{post.image}}"/>
<cite>by {{post.author}} on {{ post.createdOn | date:'medium' }}</cite>
<div class="post-body">
<p>{{post.body}}</p>
</div>
<div ng-controller="CommentCtrl as CmtCtrl">
<button class="icon-button" ng-click="post.likes = post.likes+1">
<i class="fa fa-thumbs-up"></i> {{post.likes}}
</button>
<button class="icon-button" ng-click="post.dislikes = post.dislikes+1">
<i class="fa fa-thumbs-down"></i> {{post.dislikes}}
</button>
<h3> Comments <h3>
<form class="form-style" name="commentForm" ng-submit="commentForm.$valid && CmtCtrl.addComment(post)" novalidate>
<h4> Add Comment: </h4>
<div>
<input type="text" class="comment-form form-control input-lg" name="body" ng-model="commentData.body" required placeholder="Please Leave Your Comment Here!"/>
</div>
<h4> Name: </h4>
<div>
<input type="text" class="comment-form form-control input-sm" name="author" ng-model="commentData.author" required placeholder="Name"/>
</div>
<div>
<button type="submit" class="btn comment-button button-style intro-social-buttons">Submit</button>
</div>
<!--<textarea class="comment-form" ng-model="CmtCtrl.comment.body" cols="30" rows="6" required></textarea></br>
<label for=""> <h4>Name:</h4> </label></br>
<input class="comment-form" type="text" ng-model="CmtCtrl.comment.author" required placeholder="Name"/></br>
<input class="btn comment-button button-style intro-social-buttons" type="submit" value="Submit"></br>-->
</form>
<ul>
<li ng-repeat="comment in post.comments">
"{{comment.body}}"
<cite>- <b>{{comment.author}}</b></cite>
</li>
</ul>
</div>
</div>
</div>
Also, to note that I use Mongoose and my schema allows body, author and date. I made it a nested array within my blog database as I wanted it to be attached to the individual blog post.
Let me know if there is anything else I can answer or give any other files.
Thanks

Resources