How to send data from input to service? - javascript

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);
}
}]);

Related

put facebook login data into textfields with angualrjs

I'm implementing facebook login and its working alright with angular.but the problem is when i get the data from facebook i'm unable to put in a textfield. when i put it in an alert its able to give me the data but can't put it in a textfield.
<div ng-controller="facebook_login">
<p align="center"><button class="icon icon-left ion-social-facebook button button-positive button-small" ng-click="fbLogin()">Sign Up with Facebook</button></p>
<div class="list">
<div class="item">
<label class="item item-input item-stacked-label">
<span class="input-label">Fashion Line</span>
<input type="text" ng-model="email" ng-value="{{data.email}}" />
<div>
JS
.controller('facebook_login',['$scope', '$ionicModal', '$timeout', 'ngFB', function($scope, $ionicModal, $timeout, ngFB) {
$scope.fbLogin = function () {
ngFB.login({scope: 'email,public_profile,publish_actions'}).then(
function (response) {
if (response.status === 'connected') {
//alert('Facebook login succeeded, got access token: ' + response.authResponse.accessToken);
//$scope.closeLogin();
ngFB.api({
path: '/me',
params: {fields: 'first_name,last_name,gender,email,picture'}
}).then(
function (data) {
$scope.facebook = data;
alert(data.email)
$scope.email = $scope.data.email;
document.getElementById("email").innerHTML = data.email;
});
} else {
alert('Facebook login failed');
}
});
};
}])
Seems like you never defined $scope.data but you're trying to use it. Did you mean $scope.facebook.email instead?

AngularJS : How to get returned value from factory

I am very much new in AngularJS and I have the following problem:
View:
<div>
<form role="form" name="loginForm" class="form-horizontal login-form">
<div class="form-group">
<p class="login-form-msg">Welcome : {{user.username}}</p>
<label for="inputUserName" class="col-sm-2 control-label login-form-label">Base</label>
<div class="col-sm-10">
<input type="text" placeholder="Enter base" class="form-control" required ng-model="user.code">
</div>
</div>
<div class="form-group">
<label for="inputUserName" class="col-sm-2 control-label login-form-label">Username</label>
<div class="col-sm-10">
<input type="text" placeholder="Enter name" class="form-control" required ng-model="user.username">
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-sm-2 control-label login-form-label">Password</label>
<div class="col-sm-10">
<input type="password" placeholder="Password" id="inputPassword" class="form-control" required ng-model="user.password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10 login-form-button">
<button class="btn btn-default" type="submit" ng-disabled="loginForm.$invalid" ng-click="login(user)">Sign in</button>
</div>
<p class="login-form-msg">{{msgtxt}}</p>
</div>
</form>
</div>
Main js:
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'partials/login.html',
controller:'loginCtrl'
});
$routeProvider.when('/welcome', {
templateUrl: 'partials/welcome.html',
controller:'loginCtrl'
});
$routeProvider.otherwise({ redirectTo: '/login' });
}]);
I have the following factory:
myApp.factory('getURLService', function ($http, config) {
return {
getURL: function (user,scope) {
$http.get(config.backend + "/Device/GetURLbyCode", {
params: { code: user.code }
})
.success(function (data) {
var url = '';
if (data.status == 'succ') {
url = data.Result;
}
else {
scope.msgtxt = data.msg;
}
return url;
});
}
}
});
I need to use the returned value from this factory in other factories.
For example in my login factory:
myApp.factory('loginService', function ($http, $location, config) {
return {
login: function (user,url,scope) {
$http.get(url + "/Device/Register", {
params: { userName: user.username, password: user.password }
})
.success(function (data) {
if (data.status == 'succ') {
$location.path('/welcome');
}
else {
scope.msgtxt = data.msg;
}
});
}
}
});
This is my controller:
myApp.controller('loginCtrl', function ($scope, getURLService, loginService) {
$scope.msgtxt = '';
$scope.login = function (user) {
loginService.login(user,url,$scope); //call login service
}
});
What do I need to do in my controller to actually return the url and then send it to the login service or any other service (or even controller) in the future?
Thanks in advance for your time and suggestion.
For returning data from the function you should return promise object which $http.get already returns it.
Additional thing which I wanted to point out is, passing $scope to the service disobey the rule of singleton, as you are creating a service which is dependent of the controller scope. Service should only accept the parameter and return the result by processing it, nothing else.
Code
return {
getURL: function (user,scope) {
return $http.get(config.backend + "/Device/GetURLbyCode", {
params: { code: user.code }
})
.then(function (res) {
var data = res.data;
var url = '';
if (data.status == 'succ') {
url = data.Result;
}
else {
scope.msgtxt = data.msg;
}
return url;
});
}
}
LoginService
myApp.factory('loginService', function ($http, $location, config) {
return {
login: function (user,url) {
return $http.get(url + "/Device/Register", {
params: { userName: user.username, password: user.password }
})
.then(function (response) {
var data = response.data;
if (data.status == 'succ') {
$location.path('/welcome');
return;
}
return data.msg;
});
}
}
});
Controller
getURLService.getURL(user).then(function(url){
//assuming you already having value of user available here
loginService.login(user,url).then(function(message){ //call login service
if(message)
$scope.msgtxt = message;
});
});

Angular ng-click cannot get value of ng-model

I am working with a form and I literally just want to get the value from an ng-model. the form looks like this:
<form name="comment_form" class="row" novalidate>
<div class="col col-80 content col-center">
<input class="new-comment-message" type="text" style="margin-left: 15px;" placeholder="Leave a comment..." ng-model="new_comment" required></input>
</div>
<div class="col col-20 button-container col-center">
<button class="button button-clear send" type="submit" ng-click="addComment()" ng-disabled="comment_form.$invalid">
Send
</button>
</div>
</form>
This is my whole controller. The end result is to post a comment to wordpress however With my form content returning undefined its a bit difficult. (P.S. its posting to wordpress and the comment is just saying 'undefined'):
.controller('EasternInnerCtrl', function ($http, $timeout, $scope, $ionicLoading, $stateParams, $ionicScrollDelegate, $cordovaSocialSharing, $ionicModal, Easternc, AuthService) {
$scope.eastc = Easternc.get($stateParams.eastcId);
$ionicModal.fromTemplateUrl('commenter.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal
})
$scope.openModal = function() {
$scope.modal.show()
}
$scope.closeModal = function() {
$scope.modal.hide();
};
$scope.$on('$destroy', function() {
$scope.modal.remove();
});
$scope.addComment = function(){
$ionicLoading.show({
template: 'Submiting comment...'
});
console.log($scope.new_comment);
Easternc.submitComment($scope.eastc.id, $scope.new_comment).then(function(data){
if(data.status=="ok"){
var user = AuthService.getUser();
var comment = {
author: {name: user.data.username},
content: $scope.new_comment,
date: Date.now(),
user_gravatar : user.avatar,
id: data.comment_id
};
console.log($scope.new_comment);
/*$scope.eastc.comments.push(comment);
console.log(comment);
$scope.new_comment = "";
$scope.new_comment_id = data.comment_id;
$ionicLoading.hide();
$ionicScrollDelegate.scrollBottom(true);*/
}
});
};
$scope.sharePost = function(link){
console.log(link);
window.plugins.socialsharing.share('I just read this article on blah: ', null, null, url);
};
})
my console log is showing: undefined when I click send though?
I'm pretty sure the modal got an isolated scope. It means $scope.new_comment wont exists in your controller.
You should try this :
$scope.addComment = function(comment){
Easternc.submitComment($scope.eastc.id,comment).then(function(data){
console.log(comment);
});
};
with this in your html
<button class="button button-clear send" type="submit" ng-click="addComment(new_comment)" ng-disabled="comment_form.$invalid">
Send
</button>
Hope it helped.

Angularjs: View not updating list after POST

I am currently working on a small angularjs app which is basically a user profile management app.
The problem i am having is with adding users dynamically. When i enter the user data, it successfully POST's to my local server i have setup, BUT i have to refresh the page to see the new user in the users list
I obviously dont want to have to refresh.
-Yes i've tried $scope.apply() after running the POST function
Something i am noticing with Angular Batarang (Debugging tool), is that the scope is updating fine, but there is a blank spot or 'null' value where the new user should be.
Here are the Controllers:
UsersApp.controller('UserListController', [ '$scope', 'userService', function($scope, userService) {
$scope.usersList = userService.usersList;
$scope.users = userService.users;
$scope.user = userService.user;
}]);
UsersApp.controller('AddUserController', function($scope, $window, dataResources, userService) {
$scope.addNew = function addNew(newUser) {
$scope.usersList = userService.usersList;
var firstName = newUser.firstName;
var lastName = newUser.lastName;
var phone = newUser.phone;
var email = newUser.email;
$scope.newUserData = {
firstName , lastName, phone , email
}
new dataResources.create($scope.newUserData);
$scope.usersList.push(dataResources);
$scope.$apply();
};
And Here are my views:
Add User:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="js/minimize.js"></script>
<div ng-controller="AddUserController">
<div class="userInfo" id="usernameDiv">
<h2 id="username">User<img id="showhide" src="images/plus.png" style="position:absolute; padding-left:15px; width:31px; color:white;"></h2>
</div>
<div class="userInfo">
<div id="listInfo">
<form ng-controller="AddUserController">
<input type="text" placeholder= "First Name" ng-model="newUser.firstName"></input>
<input type="text" placeholder= "Last Name" ng-model="newUser.lastName"></input>
<input type="text" placeholder= "Phone Number" ng-model="newUser.phone"></input>
<input type="text" placeholder= "Email" ng-model="newUser.email"></input>
<button type="submit" ng-click="addNew(newUser)">Add User</button>
</form>
</div>
</div>
Users List:
<!DOCTYPE html>
<html>
<head></head>
<body id="">
<div ng-controller="UserListController">
<div class="userInfo">
<h2>List of Users</h2>
<div id="listInfo">
<ul style="list-style-type: none;">
<li ng-repeat="user in usersList">
<!--<p class="userData">ID: {{ user }}</p> -->
<p class="userData"><a style="cursor:pointer;" ui-sref="UserProfile">{{ user.firstName }}</a></p>
</li>
</ul>
</div>
</div>
Factory and Service:
UsersApp.factory('dataResources', [ '$resource', function($resource) {
return $resource('http://localhost:24149/users/:id', {}, {
query: {method:'GET', params:{idnum: '#id'}, isArray:true},
create: {method:'POST', headers: { 'Content-Type': 'application/json' }},
update: {method:'PUT', params:{idnum: '#id'}},
remove: {method:'DELETE', params:{idnum:'#id'}, isArray:true}
});
}]);
UsersApp.service('userService', function(dataResources) {
return {
usersList: dataResources.query()
}
});
I'm not sure if I follow exactly, but I believe you need to deal with a promise from your POST and then push the result. e.g.,
dataResources.create($scope.newUserData).$promise.then(function(data) {
$scope.usersList.push(data);
});
Your service will return a promise and then when the POST is complete your service should return the new user and you just add it to your current list.
See $resource documentation:
non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
According to the doc your code should look like this:
dataResources.create($scope.newUserData,
function(data) {
$scope.usersList.push(data);
}
);
controller: you don't need to make a new userdata object, you can just use newUser
UsersApp.controller('AddUserController', function($scope, $window, dataResources, userService) {
$scope.usersList = userService.usersList;
$scope.addNew = function addNew(newUser) {
dataResources.create($scope.newUser,
function(data) {
$scope.usersList.push(data);
}
);
};
};
Same idea for angular2 using observables.
public posts: any;
onPost(input) {
this.dataService.jsonserverPost(input)
.subscribe(
(data: any) => {
this.posts.push(data);
}
);
}

Angular post to nodejs

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.
};

Categories