Angular post to nodejs - javascript

I just wanna post some changes to the database. This is my angular - the problem is, it dosn't take values from my html inputs.
See section 2 of code:
mainController = function ($scope, $http) {
$scope.post = {};
console.log($scope);
console.log($scope.post);
$http.get('/api/todos')
.success(function(data) {
$scope.posts = data.posts;
$scope.datas = data;
// console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
$scope.editTodo = function() {
console.log($scope.post);
$http.post('/post/edit', $scope.post)
.success(function(data) {
$scope.post = {};
console.log($scope.post);
$scope.posts = data.posts;
$scope.datas = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}
Section 2:
<div class="comment" ng-repeat="post in posts | filter:search:strict | orderBy:predicate:reverse">
<div class="comment-content">
<form>
<input type="text" class="" ng-model="post.id" />
<input type="text" class="h2" ng-model="post.title" />
<textarea ng-model="post.content" ></textarea>
<span class="submitcontent" ng-click="editTodo()">
Submit
</span>
</form>
</div>
</div>
I don't get why my $scope.post obj is allways equal to: Object {} and my log from the node server shows:
{ id: undefined, postTitle: undefined, postContent: undefined }
POST /post/edit 200 8ms - 2.92kb

In your ng-repeat directive post is the current post NOT $scope.post. Just pass the post you're dealing with to your edit function:
<span class="submitcontent" ng-click="editTodo(post)">Submit</span>
JavaScript:
$scope.editTodo = function(p) {
console.log(p); // will have your id, title and content.
};

Related

String Replace With Parameter Value Angular

I am trying to populate a text area with a formatted letter, which comes from a text file. This text file contains objects like {{client.name}} and {{client.address}}, which I would like to replace with the value of the specific client's attribute. Here is the code I have this far,
$scope.loadFlyer = function() {
$http.get("/assets/clientwelcome.txt").then(function(res){
$scope.flyerdescription = res.data;
$scope.flyerdescription = $scope.flyerdescription.replace(/{{client.name}}/g, $scope.client.name);
});
};
Where previously I had called the data from the client's table:
myApp.controller('ClientCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
$scope.clients = [];
$http.get('/client').success(function(data, status, headers, config) {
$scope.clients = data;
if (data == "") {
$scope.clients = [];
}
}).error(function(data, status, headers, config) {
console.log("Ops: could not get any data");
});
And this is the field that I am trying to populate:
<div class="form-group">
<label class="control-label" for="flyer-description">Description</label>
<textarea style="height:400px" class="form-control" id="flyer-description" ng-model="flyerdescription"></textarea>
</div>
Unfortunately, no replacing is done. I've tried to format the replace as I have seen in the javascript documents, but to no avail.
Editted* per discussion below
You have a list of clients that looks like [{name: 'Hank Aaron'}, {name: 'Sandy Koufax'}, {name: 'Bo Jackson'}], and a template string, that contains a value: '{{client.name}}', that you want to replace with a name from your clients list.
myApp.controller('ClientCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
$scope.clients = [];
$http.get('/client').success(function(data, status, headers, config) {
$scope.clients = data;
if (data == "") {
$scope.clients = [];
}
}).error(function(data, status, headers, config) {
console.log("Ops: could not get any data");
});
$scope.loadFlyer = function() {
$http.get("/assets/clientwelcome.txt").then(function(res){
$scope.flyerdescription = res.data;
$scope.descriptions = [];
for(var i=0; i<$scope.clients.length; i++){
$scope.descriptions[i].push($scope.flyerdescription.replace(/{{client.name}}/g,$scope.clients[i].name));
}
});
};
}]);
and in your HTML
<div class="form-group">
<div ng-repeat="description in descriptions">
<label class="control-label" for="flyer-description">Description</label>
<textarea style="height:400px" class="form-control" id="flyer-description" ng-model="description"></textarea>
</div>
</div>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-app="demoApp" ng-controller="validationCtrl" class="form-group">
<label class="control-label" for="flyer-description">Description</label>
<textarea style="height:100px" class="form-control" id="flyer-description" ng-model="stringname
"></textarea>
</div>
<script>
//This is controller
var app = angular.module('demoApp', []);
app.controller('validationCtrl', function($scope) {
$scope.stringname = 'angular123456 test demo';
$scope.stringname = $scope.stringname.replace('test', "");
});
</script>
</body>
</html>

typeahead fetch data from url key and api angularjs

Hi I am new to Angularjs. I am trying to create a typeahead where I am fetching the data through the api. I tried searching for the solution but I dint get the solution what I was looking for. Below is the code what I have done so far.
HTML CODE:
<div ng-controller="newController">
<div class="selection-box">
<div class="title-box">
<div class="search_item">
<input name="document" ng-model='query' type="text" typeahead="document as document.name for document in documents | filter:query | limitTo:8" id='document' placeholder="SEARCH FOR YOUR DOCUMENT" class="search_box">
</div>
{{query}}
</div>
</div>
</div>
In this input box whatever I type it gets printed in the {{query}} but doesn't show any data fetching from the api. I am using bootstrap ui . Below is the controller what I wrote.
newController.js:
var myApp = angular.module('myModule', ['ui.bootstrap']);
myApp.service("searchService", function ($http) {
var apiUrl = "http://12.56.677/api/v1/mobile/";
var apiKey = "123nm";
this.searchDocument = function(query) {
var response = $http({
method: 'post',
url: apiUrl + "search",
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
params: {
key: apiKey,
query: query
}
});
return response;
};
});
myApp.controller('newController', ['$scope', 'searchService' , function($scope, searchService, $rootScope, $http, $window, $document) {
var apiUrl = "http://12.56.677/api/v1/mobile/";
var apiKey = "123nm";
url = apiUrl + "search";
Key = apiKey;
$scope.query = undefined;
console.log(query);
searchService.searchDocument(query='').then (function (res) {
if(res.data.status == "OK")
{
$scope.documents = res.data.result;
console.log($scope.documents);
// var userinformation = res.data.result;
// $window.localStorageService.setItem('searchDocument', JSON.stringify(query));
}
else {
$scope.errorMessage = res.data.message;
}
})
}])
Any help would be appreciated.
What you attempted to do is using typeahead with a pre-fetched list (an with an empty query).
You probably want to do asynchronous search and would need a data fetch function to do so.
HTML, note the typeahead expression:
<input name="document" ng-model='query' type="text"
typeahead="document as document.name for document in (getDocuments() | limitTo:8)"
id='document'
placeholder="SEARCH FOR YOUR DOCUMENT" class="search_box">
Controller:
myApp.controller('newController', ['$scope', 'searchService' , function($scope, searchService, $rootScope, $http, $window, $document) {
var apiUrl = "http://12.56.677/api/v1/mobile/";
var apiKey = "123nm";
// What are these two undeclared variables lying here around for?
url = apiUrl + "search";
Key = apiKey;
$scope.getDocuments = function(query){
searchService.searchDocument(query) // Check your API, I am not sure how you're API treats these parameters
.then (function (res) {
if(res.data.status == "OK")
{
var documents = res.data.result;
console.log(documents);
return documents;
}
else {
$scope.errorMessage = res.data.message;
return [];
}
})
}
}])
I think you need to return promise from the searchService.searchDocment() as below:
return searchService.searchDocument(query='').then(......)
//HTML
<input name="document"
ng-model='query' type="text"
uib-typeahead="document as document.name
for document in documents |filter:query | limitTo:8" id='document'
placeholder="SEARCH FOR YOUR DOCUMENT" class="search_box">
//Controller
searchService.searchDocument('').then (function (res) {
if(res.data.status == "OK"){
$scope.documents = res.data.result;
}
else {
$scope.errorMessage = res.data.message;
}
});

How to send data from input to service?

I have a problem with a sending data form input to the service.
For example I have an input:
<input type="text" class="form-control" placeholder="City name...">
<span class="input-group-btn">
<button class="btn btn-default" type="button">Go!</button>
</span>
And a service which is geting data for rest api:
app.factory('forecast', ['$http', function($http) {
return $http.get('http://api.openweathermap.org/data/2.5/forecast/city?q=Warsaw&units=metric&mo')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
How can I send the city name from the input after clicking button "Go" to construct my own api link ? And then display those data in view ?
I mean something like this http://api.openweathermap.org/data/2.5/forecast/city?q=VALUE_FROM_THE_INPUT&units=metric&mo
You should assign your input an ng-model directive, like this:
<input type="text" class="form-control" placeholder="City name..." ng-model="city.name">
Assign your button an ng-click directive, like this:
<button class="btn btn-default" type="button" ng-click="getForecast(city)">Go!</button>
Finally, add getForecast function to your controller, like this:
$scope.getForecast = function (city) {
forecast.getForecast($scope.city).then(function (data) {
// do something with the response
}, function (err) {
// do something about the error
});
}
For this to work you should change your service to something like this:
app.factory('forecast', ['$http', function($http) {
return {
getForcast: function (city) {
$http.get('http://api.openweathermap.org/data/2.5/forecast/city?q=' + city.name + '&units=metric&mo');
}
};
}]);
your HTML :
<input type="text" class="form-control" placeholder="City name..." ng-model="city">
<span class="input-group-btn">
<button class="btn btn-default" type="button" ng-click="go()">Go!</button>
</span>
your Factory :
app.factory('forecast', ['$http', function($http) {
this.sendAPIRequest = function(city){
$http.get('http://api.openweathermap.org/data/2.5/forecast/city?q='+city+'&units=metric&mo')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
};
return this;
}]);
your Controller :
app.controller('myCtrl', ['$scope', 'forecast', function ($scope, forecast) {
$scope.go = function(){
$scope.data = forecast.sendAPIRequest($scope.city);
};
}])
You seem to be asking a few questions, but lets just start with the "GO" to link using input. since you're using an angular factory you may want to use a controller or something:
HTML:
<div ng-controller="formCtrl">
<input type="text" class="form-control" placeholder="City name..." ng-model="city">
<span class="input-group-btn">
<button class="btn btn-default" type="button" ng-click="goToUrl(city)">Go!</button>
</span>
</div>
now you want to pass that city to the url name?
app.factory('forecast', ['$http', function($http) {
var forecastFactory = {};
forcastFactory.customUrl = function(city){
$http.get('http://api.openweathermap.org/data/2.5/forecast/city?' + city +'q=Warsaw&units=metric&mo')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
return forecastFactory;
}]);
app.controller('formCtrl', ['forecast', function(Forecast){
$scope.goToUrl = function(name){
var data = Forecast.customUrl(name);
}
}]);

AngularJs json URL changer

I'm working on some mega simple weather app in Angular for practice reasons and i'm stuck..
i have a angular json feed like this:
app.factory('forecast', ['$http', function($http) {
return $http.get('http://api.openweathermap.org/data/2.5/weather?q=Amsterdam,NL&lang=NL_nl&units=metric')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
and it loads the feed in to the index.html. its all working and what i wand now is a input form on index that changes the Amsterdam part of the url on js/services/forcast.js where the above code is to another city so people can see their city weather.
See the demo here: http://dev.bigstoef.nl/workspace/shiva/weer/index.html
Ive tryd about all posable options about now and i'm 3 days further and its a no go. What is there correct way here?
First, create a "configurable" service :
app.factory('forecast', ['$http', function($http) {
var city;
var cities = {
amsterdam: 'Amsterdam,NL',
paris: 'Paris,FR'
};
var api_base_url = 'http://api.openweathermap.org/data/2.5/weather';
var other_params = 'lang=NL_nl&units=metric';
return {
setCity: function(cityName){
city = cityName ;
console.log(city);
},
getWeather: function(cityName){
console.log(city);
if(cityName) this.setCity(cityName);
if (!city) throw new Error('City is not defined');
return $http.get(getURI());
}
}
function getURI(){
return api_base_url + '?' + cities[city] + '&' + other_params;
}
}]);
Then you can create a controller like the following:
app.controller('forecastCtrl', ['$scope', 'forecast',function($scope,forecast){
$scope.city = 'amsterdam' ;
$scope.$watch('city',function(){
console.log($scope.city);
forecast.setCity($scope.city);
});
$scope.getWeather = function(){
console.log('get weather');
forecast.getWeather()
.success(function(data){
console.log('success',data);
$scope.weatherData = data;
}).error(function(err){
console.log('error',err);
$scope.weatherError = err;
});
};
}]);
To implement a template as the following
<link rel="stylesheet" href="style.css" />
<div data-ng-controller="forecastCtrl">
<form>
<label>
<input type="radio" name="city" data-ng-model="city" data-ng-value="'amsterdam'">Amsterdam
</label>
<br/>
<label>
<input type="radio" name="city" data-ng-model="city" data-ng-value="'paris'">Paris
</label>
<br/>
<button data-ng-click="getWeather()">Get Weather</button>
</form>
<p class="weather-data">
{{weatherData}}
</p>
<p class="weather-error">
{{weatherError}}
</p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="script.js"></script>
You can view the code working here : http://plnkr.co/edit/rN14M8GGX62J8JDUIOl8?p=preview
You can return a function in your factory. Define your forcast as
app.factory('forecast', ['$http', function($http) {
return {
query: function(city) {
return $http.get('http://api.openweathermap.org/data/2.5/weather?q=' + city + '&lang=NL_nl&units=metric')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
};
}]);
Then in your controller
forecast.query('Amsterdam,NL').success(function(data) {
$scope.weer = data;
});
Change service code to have a dedicated method which you can call multiple times with different parameters (cities):
app.factory('forecast', ['$http', function($http) {
return {
load: function(location) {
return $http.get('http://api.openweathermap.org/data/2.5/weather?q=' + location + '&lang=NL_nl&units=metric')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
}
}]);
Then in controller you would be able to load forecat for other locations when you need:
forecast.load('Amsterdam,NL').then(function(data) {
$scope. weer = data;
});
Demo: http://plnkr.co/edit/GCx35VxRoko314jJ3M7r?p=preview

How to write an angularJs Controller to GET Rest Data from Parse.com

See solution below:
I'm trying to connect to a Parse.com Rest backend and display data from object values.
HTML (I put several angular calls to be sure to catch output):
<div ng-controller="MyController">
<p>{{item}}<p>
<p>{{items}}<p>
<p>{{item.firstName}}<p>
<p>{{data}}<p>
</div>
JAVASCRIPT rest:
function MyController($scope, $http) {
$scope.items = [];
$scope.getItems = function() {
$http({method : 'GET',url : 'https://api.parse.com/1/classes/Professional/id', headers: { 'X-Parse-Application-Id':'XXXX', 'X-Parse-REST-API-Key':'YYYY'}})
.success(function(data, status) {
$scope.items = data;
})
.error(function(data, status) {
alert("Error");
});
};
}
This won't work, it does strictly nothing, not even a message in the console.
I know the rest call got the correct credential, as I'm able to get object content returned when I test it with a rest tester program. Maybe the URL should not be absolute ?
Any clue is very welcome, i've spent DAYS on that.
SOLUTION:
Thanks to the help of people answering this thread, I was able to find the solution to this problem so I just wanted to contribute back:
Get Json object data from Parse.com backend, pass it authentification parameters:
function MyController($scope, $http) {
$scope.items = [];
$scope.getItems = function() {
$http({method : 'GET',url : 'https://api.parse.com/1/classes/Professional', headers: { 'X-Parse-Application-Id':'XXX', 'X-Parse-REST-API-Key':'YYY'}})
.success(function(data, status) {
$scope.items = data;
})
.error(function(data, status) {
alert("Error");
});
};
Notice that ' ' necessary arround header key object values. Those ' ' are not necessary around method and url keys.
Template that list all 'firstName' of each object:
<div ng-controller="MyController" ng-init="getItems()">
<ul>
<li ng-repeat="item in items.results"> {{item.firstName}} </li>
</ul>
</div>
Notice: "item in items.results". "results" is necessary because the return value is a JSON object that contains a results field with a JSON array that lists the objects. This could save you some headache.
Also notice "ng-init": if you don't put that, or any other form of call to the getItem(),then nothing will happen and you will be returned no error.
That was my first try of Angularjs, and i'm already in love ^^.
Based in your request the controller should be:
HTML
<div ng-controller="MyController">
<button type="button" ng-click="getItems()">Get Items</button>
<ul>
<li ng-repeat="item in items"> item.firstName </li>
</ul>
</div>
JS
function MyController($scope, $http) {
$scope.items = []
$scope.getItems = function() {
$http({method : 'GET',url : 'https://api.parse.com/1/classes/Users', headers: { 'X-Parse-Application-Id':'XXXXXXXXXXXXX', 'X-Parse-REST-API-Key':'YYYYYYYYYYYYY'}})
.success(function(data, status) {
$scope.items = data;
})
.error(function(data, status) {
alert("Error");
})
}
}
Just a little update to the newer versions of Angular (using .then since version 1.5):
myApp.controller('MyController', function($scope, $http) {
$scope.items = []
$http({
method: 'GET',
url: 'https://api.parse.com/1/classes/Users',
headers: {'X-Parse-Application-Id':'XXXXXXXXXXXXX', 'X-Parse-REST-API-Key':'YYYYYYYYYYYYY'}
})
.then(function successCallback(response) {
alert("Succesfully connected to the API");
$scope.items = data;
}, function errorCallback(response) {
alert("Error connecting to API");
});
});
var app = angular.module("app",[]);
app.controller("postcontroller", function($scope, $http){
$scope.getAllProjects = function() {
var url = 'https://reqres.in/api/products';
$http.get(url).then(
function(response) {
$scope.projects = response.data.data;
},
function error(response) {
$scope.postResultMessage = "Error with status: "
+ response.statusText;
});
}
$scope.getAllProjects();
});
<div ng-app="app">
<div ng-controller="postcontroller">
<div class="panel-body">
<div class="form-group">
<label class="control-label col-sm-2" for="project">Project:</label>
<div class="col-sm-5">
<select id="projectSelector" class="form-control">
<option id="id" ng-repeat="project in projects"
value="{{project.id}}">{{project.name}}</option>
</select>
</div>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>

Categories