I have some in put in my form.
<input type="text" name = "alias" placeholder="Start Time" style="width:200px"/><br/>
<button ng-click="new()" name="new" >Add</button>
How can I pass input value to server to make new user in mongoDb.
The client controller:
$scope.new = function(){
//$scope.user.$save({ id: $scope.user._id }, function() {
// $scope.users = User.query();
// how can I pass from here
});
}
I can get this value in the server controller.js
function json_user_save(id) {
var self = this;
// self.model('user').Schema;
// framework.model('user').Schema;
var User = MODEL('user').Schema;
console.log('save ->', id);
// What is it? https://github.com/totaljs/examples/tree/master/changes
self.change('user: save, id: ' + id);
var model = self.body;
var user = new User({ alias: model.alias, created: new Date() }).save(function(err) {
if (err)
self.throw500(err);
// Read all users
User.find(self.callback());
});
}
How can I pass value from angularjs to server?
User $http.post method (https://docs.angularjs.org/api/ng/service/$http) and ng-submit directive (https://docs.angularjs.org/guide/forms)
An even better solution would be the use the Restangular library on top of Angular.
https://github.com/mgonto/restangular#collection-methods
Related
In front page there are two options:
1.create new
2.edit
1.it goes to index.html
2.it should be goes to index html with data(data should be load from database)
//get data from database
$scope.getItem = function(id) {
var auth = btoa("root:root");
$scope.form["#class"] = "ProjectDetails";
$http.defaults.headers.common.Authorization = 'Basic ' + auth;
$http.get("http://azuspeedcp01:2480/document/InternalRPA/"+id+"/*:-1", {
})
.then(function(response) {
console.log(response);
$scope.form=response.data;
});
}
here i retrieve data from db is fine.its response.data
again assign to $scope.form which is the object i passed from form to submit data.
//index.html(partial)
<input type="text" id="clientName" ng-model="form.ClientName">
<input type="text" id="initiate" ng-model="form.City">
<select id="Geo" ng-model="form.Geo">
<option value="North America">North America</option>
</select>
How to route to index.html with data. I don't have idea.please help me.
it goes to index.html
it should be goes to index html with data(data should be load from database)
So you want always staying in the same screen, then why you want to redirect(refresh) on the same screen? You can use the same scope object anywhere in the same screen(index.html),
it should be goes to index html with data(data should be load from database)
If you want to redirect with data. then Just use location.$path("routename") to redirect the screen and maintain the values by using $localStorage
I found the answer that I can use angular service to route from one service to another.Thanks all to help me
app.service('srvShareData', function($window) {
var KEY = 'App.SelectedValue';
var addData = function(newObj) {
alert("2"+newObj);
$window.sessionStorage.setItem(KEY,JSON.stringify(newObj));
};
var getData = function(){
var mydata = $window.sessionStorage.getItem(KEY);
return mydata;
};
return {
addData: addData,
getData: getData
};
})
I'm trying to submit a form from a HTML page using angular.
My HTML code is:
<form role="search">
<input type="text" ng-model="searchSring">
<button type="submit" ng-click="searchPerson(searchString);">Get it!
</button>
</form>
The searchPerson function is calling some PHP page using Ajax and data is successfully retrieved from it.
What I want is when the user has clicked the Get it! button, he should be routed to another HTML page where I would like to display the results. I've tried using "action=" in the form and even calling window.location once Ajax completed to route to the next page. Every time the result is cleared. I've tried using factory with get/set, but this too clears the data on the second page after the window.location call.
Here's the factory code:
myApp.factory('searchService', function(){
var searchService = {};
var mySearchResult = {};
searchService.set = function(searchResult){
mySearchResult = searchResult;
}
searchService.get = function(text){
return mySearchResult;
}
return searchService;
});
CONTROLLER
myApp.controller('OnlineCVController', function($scope, searchService) {
$scope.searchPerson = function(personString) {
$.ajax({
url: "mySearch.php",
type: 'POST',
data: { Person: personString },
async: false, success: function (result) { searchService.set(result);
console.log(result);
window.location = "search.html";
}, error: function (result) { } });
}
Can anyone guide me further?
I am using Angularfire and I'd like to save data by multiple checkbox.
HTML
<form role="form" ng-submit="addTask(task)">
<label class="checkbox-inline" ng-repeat="(key, value) in students">
<input type="checkbox" id="{{key}}" value="{{key}}" ng-model="task.student[value.name]">{{value.name}}
</label>
<button type="submit">Submit</button>
</form>
JS
var ref = new Firebase(FURL);
var fbTasks = $firebaseArray(ref.child('tasks'));
$scope.addTask = function(task) {
fbTasks.$add(task);
}
This was the result
student
--Alison Kay: true
--Jessica Cook:false
--John Smith: true
--Kevin Hunt: true
My question is there any way to save them like this?
student
--(key)
--name:Alison Kay
--checked: true
--(key)
--name:Jessica Cook
--checked: false
--(key)
--name:John Smith
--checked: true
--(key)
--name:Kevin Hunt
--checked: true
I threw together a rough example PLNKR to demonstrate one way to do this by extending the AngularFire services.
Note that the documentation states:
These techniques should only be attempted by advanced Angular users who know their way around the code.
Solution
You can create a factory that extends $firebaseObject, and adds a method .addTask() which uses .push() to generate a new key for a new task.
Factories:
app.factory("TaskList",function($rootScope, $q, fbUrl, TaskListFactory){
return function(studentKey){
var ref = new Firebase(fbUrl+'/tasks/'+studentKey);
return new TaskListFactory(ref);
}
});
app.factory("TaskListFactory",function($firebaseObject, $q, fbUrl, $rootScope){
return $firebaseObject.$extend({
addTask: function(name, checked){
// use push to generate a new key, set `name` and `checked`
this.$ref().push({name: name, checked: checked}, function(error){
if(!error){
console.error(error);
} else {
console.log("Pushed new task.");
}
});
}
});
});
Controller:
Note: I used mock objects. I couldn't decode your data structure, and took a best guess approach.
app.controller('HomeController',function($scope,fbUrl, $firebaseObject, TaskList) {
// create mock student and task
$scope.students = {tester: {name: 'tester'} };
$scope.task = {tester: {name: 'test this'}};
var taskList = new TaskList('student123');
// get tasks list for debug:
var tasksRef = new Firebase(fbUrl+'/tasks');
$scope.tasks = $firebaseObject(tasksRef);
$scope.addTask = function(task) {
console.debug(task);
taskList.addTask('Tester McGee', task.student['tester']);
}
});
Result (<firebaseUrl>/tasks):
{
"$id": "tasks",
"$priority": null,
"student123": {
"-JoMxWoX0tQrGtdP6Qvm": {
"checked": true,
"name": "Tester McGee"
}
}
}
Again, the focus of this is on the factories, and not on the data structure. The form data in my example doesn't make sense.
Hope that helps.
I want $http.get method to work when a form is submitted.
Here is my code. The object $scope.questions is being set when the method is called but the data doesn't show up in the div. Moreover, when the $http.get method is outside the signIn() function it works just fine.
$scope.signIn = function(data) {
$location.path('/profile');
var url = "database/fetch_data.php?query=";
var query = "Select * from question where userId=2";
url += query;
$http.get(url).success(function(questionData) {
$scope.questions = questionData;
console.log($scope.questions);
});
};
<div>
User Profile
<br/>Question Posted
<br/>
<input ng-model="query.title" id="value" type="text" placeholder="Search by Title..." ">
<div>
<ul>
<li ng-repeat="question in questions | filter: query ">
{{question.title}}
</li>
</ul>
</div>
<br/>
</div>
You need to move your $location.path('/profile') inside your http request. Remember that a http request is async call. You should redirect after getting the data not before.
$scope.signIn = function(data) {
var url = "database/fetch_data.php?query=";
var query = "Select * from question where userId=2";
url += query;
$http.get(url).success(function(questionData) {
$scope.questions = questionData;
console.log($scope.questions);
$location.path('/profile');
});
};
If you're redirecting to another route with a completely separate scope you will lose any scope you're setting in the success handling.
From what I'm reading you're clicking a button to do an action. After that action you're redirecting to another page with a separate controller and trying to persist the data.
Unfortunately, Angular hasn't figured out a great way to do this. The easiest way to persist data through controllers and scope is to create a service that will store it in one controller and grab it in another controller.
For instance:
$scope.signIn = function(data) {
var url = "database/fetch_data.php?query=";
var query = "Select * from question where userId=2";
url += query;
$http.get(url).success(function(questionData) {
$location.path('/profile');
storageService.store("question", questiondata)
});
};
Your new factory to persist data through:
angular.module('moduleName').factory('storageService', [
function () {
return {
store: function (key, value) {
localStorage.setItem(key, JSON.stringify(value));
},
get: function(key) {
return JSON.parse(localStorage.getItem(key));
},
remove: function(key) {
localStorage.removeItem(key);
}
}
}
]);
Other controller to access data:
$scope.question = storageService.get("question");
// remove localstorage after you've grabbed it in the new controller
storageService.remove("question");
An alternative to doing the somewhat 'hacky' way of using localStorage to persist data through controllers is to use ui-router and have a resolve on the route you're redirecting to.
For instance:
$scope.signIn = function(data) {
$state.go('profile');
};
In your route file:
.state('profile', {
url: '/profile'
controller: profileControllerName,
templateUrl: 'profileHtmlTemplate.html',
resolve: {
'questions': [function() {
var url = "database/fetch_data.php?query=";
var query = "Select * from question where userId=2";
url += query;
$http.get(url).success(function(res) {
return res.data;
});
}]
}
}
In your profile controller:
Inject your 'questions' resolve into your controller and assign `$scope.question = questions;
This will make the HTTP call as soon as you click the route, return the data if successful, then render the page. It will NOT render the page if the resolve does not return success. This will ensure your data will be loaded before you load the page that depends on that data.
I would highly recommend using services to hold your HTTP calls for specific parts of your application. If you have a GET questions, POST question, PUT question. I would create a questionService and make all my HTTP methods there so you don't have to clutter your routes. You would only have to call:
.state('profile', {
url: '/profile'
controller: profileControllerName,
templateUrl: 'profileHtmlTemplate.html',
resolve: {
'questions': [function() {
return questionService.getQuestions(id).then(function(res) {
return res.data;
})
}]
}
}
I have very simple question about getting data from WebSql
I have DropDown i.e
<select id="selectCatagoryFood" data-role="listview" data-native-menu="true"
ng-init="foodCatagory = foodCatagories.cast[0]"
ng-options="foodCatagory as foodCatagory.text for foodCatagory in foodCatagories.cast"
ng-model="foodCatagory"
ng-change="changeFoodCatagory()">
</select>
now i want to add data init from webSQL. I already get Data from webSql but i am confuse that how to add that data into DropDown
An example or hints maybe very helpful for me.
Update 1 :: Add Controller Code
myApp.controller('foodSelection',function($scope,foodCatagories){
$scope.foodCatagories = foodCatagories;
$scope.changeFoodCatagory = function(){
alert($scope.foodCatagory.value);
}
});
Update 2 webSQL and JayData
_context.onReady({
success: showData,
error: function (error){
console.log(error);
}
});
function showData(){
var option = '';
_context.FoodGroup.forEach(function(FG)
{
option += '<option value="'+FG.FoodGroupID+'">'+FG.Description+'</option>';
}).then(function(){
console.log(option);
});
}
Update 3
var myApp = angular.module('myApp',[]);
myApp.factory('foodCatagories',function(){
var foodCatagories = {};
foodCatagories.cast = [
{
value: "000",
text: "Select Any"
}
];
return foodCatagories;
});
Update 4
One thing that i didn't mention is that I am using JayData for getting data from webSQL to my App
I will try to explain how it works:
EDIT: Live demo
html
Here is your stripped down select.
<select ng-options="item as item.text for item in foodCategories"
ng-model="foodCategory"
ng-required="true"
ng-change="changeFoodCategory()">
</select>
The directive ng-options will fill automatically the option elements in your select. It will take the foodCategories variable from the $scope of your controller and foreach item in the collection, it will use the text property as the label shown (<option>{{item.text}}</option>') and it will select the whole objectitemas the value of the selectedoption. You could also refer to a property as the value like ({{item.text}}). Then yourng-modelwould be set to theid` value of the selected option.
The directive ng-model corresponds to the variable in the $scope of your controller that will hold the value of the selected option.
The directive ng-required allows you to check if a value has been selected. If you are using a form, you can check if the field is valid formName.ngModelName.$valid. See the docs for more details on form validation.
The directive ng-change allows you to execute a function whenever the selected option changes. You may want to pass the ng-model variable to this function as a parameter or call the variable through the $scope inside the controller.
If no default value is set, angular will add an empty option which will be removed when an option is selected.
You did use the ng-init directive to select the first option, but know that you could set the ng-model variable in your controller to the default value you would like or none.
js
Here I tried to simulate your database service by returning a promise in the case that you are doing an async request. I used the $q service to create a promise and $timeout to fake a call to the database.
myApp.factory('DbFoodCategories', function($q, $timeout) {
var foodCategories = [
{ id: 1, text: "Veggies", value: 100 },
{ id: 2, text: "Fruits", value: 50 },
{ id: 3, text: "Pasta", value: 200 },
{ id: 4, text: "Cereals", value: 250 },
{ id: 5, text: "Milk", value: 150 }
];
return {
get: function() {
var deferred = $q.defer();
// Your call to the database in place of the $timeout
$timeout(function() {
var chance = Math.random() > 0.25;
if (chance) {
// if the call is successfull, return data to controller
deferred.resolve(foodCategories);
}
else {
// if the call failed, return an error message
deferred.reject("Error");
}
}, 500);
/* // your code
_context.onReady({
success: function() {
deferred.resolve(_contect.FoodGroup);
},
error: function (error){
deferred.reject("Error");
}
});
*/
// return a promise that we will send a result soon back to the controller, but not now
return deferred.promise;
},
insert: function(item) {
/* ... */
},
update: function(item) {
/* ... */
},
remove: function(item) {
/* ... */
}
};
});
In your controller you set the variables that will be used in your view. So you can call your DbFoodCategories service to load the data into $scope.foodCategories, and set a default value in $scope.foodCategory that will be used to set the selected option.
myApp.controller('FoodSelection',function($scope, DbFoodCategories){
DbFoodCategories.get().then(
// the callback if the request was successfull
function (response) {
$scope.foodCategories = response; //response is the data we sent from the service
},
// the callback if an error occured
function (response) {
// response is the error message we set in the service
// do something like display the message
}
);
// $scope.foodCategory = defaultValue;
$scope.changeFoodCategory = function() {
alert($scope.foodCatagory.value);
}
});
I hope that this helped you understand more in detail what is happening!
See this example and how use $apply to update the data in scope.
in the new version we released a new module to support AngularJS. We've started to document how to use it, you can find the first blogpost here
With this you should be able to create your dropdown easily, no need to create the options manually. Something like this should do the trick:
myApp.controller('foodSelection',function($scope, $data) {
$scope.foodCatagories = [];
...
_context.onReady()
.then(function() {
$scope.foodCatagories = _context.FoodGroup.toLiveArray();
});
});
provided that FoodGroup has the right fields, of course