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
};
})
Related
I am trying to display the data to my view but $scope.plan outputs {}. I am thinking that it would output the fetched data from the initGetEdit function, console.log() inside the $http.post outputs expected data.
controller.js
var id = $stateParams.id;
$scope.plan = {}
$scope.initGetEdit = function(){
var data = { id : id }
$http.post("someUrl", data).then(function(res){
$scope.plan = res.data;
console.log($scope.plan); //----> logs expected data
})
}
$scope.initGetEdit();
console.log($scope.plan); //----> logs {}
In my view I have something like this.
view
<input ng-model="plan.something" type="text" />
UPDATE
First thank you for those answers provided and the comments, appreciated it. It gives me an insight. I solved my issue by removing the initGetEdit function and staying with just the http.post.
Try keeping the second console in watch.
$scope.$watch('plan',function(){
console.log($scope.plan);
});
At first, you declare a variable $scope.plan = {} after that in http call of your $scope.initGetEdit function its empty object after the function http is an async call your object may be filled based on the response. until that it will be an empty object.
#Ujjwala Bollam mention in answer to print it in the console.
var app = angular.module('testApp',[]);
app.controller('testCtrl',function($scope,$http){
//var id = $stateParams.id;
var id=1;
$scope.plan = {}
$scope.initGetEdit = function(){
var data = { id : id }
//$http.post("http://someurl", data).then(function(res){
$scope.plan ={id:1,something:"hai this is response data"};
console.log($scope.plan); //----> logs expected data
//})
}
$scope.initGetEdit();
console.log($scope.plan); //----> logs {}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div ng-app="testApp" ng-controller="testCtrl">
<input ng-model="plan.something" type="text" />
</div>
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 trying to use angular-resource.js file in my demo .I am retrieving
data from json file using $resource and display my data using ng-repeat .But Each item I added one button (info text button).I need to get it infomation using $resource property.I am sending ID on click function .but when I am using $resource property it gives error to me
$scope.getIn=function(id){
// alert(id)
$scope.oneUser = Entry.get({user: id});
console.log($scope.oneUser)
}
here is my code
http://plnkr.co/edit/lB11oQkQjbILK36u8V25?p=preview
If i understand correctly what you are trying to achieve this should solve it:
angular.module('app',['ngResource']).controller('a',function($scope, GetData){
// read data from factory and store it in $scope.posts
GetData.then(
function successCallback(data) {
$scope.posts = data.data;
},
function errorCallback(response) {
console.log(response); // handle any errors
});
// buttonclick to return the values from the selected id
$scope.getIn = function(id){
angular.forEach($scope.posts, function(value) {
if(value.id === id)
{
$scope.selectedValue = value;
}
})
};
console.log($scope.posts)
})
.factory('GetData', function($http){ // use http to read the json
return $http.get('data.json');
});
And the html:
<body ng-app='app' ng-controller='a'>
<div ng-repeat='p in posts'>
<span>{{p.name}}</span>
<button ng-click=getIn(p.id)>info</button>
</div>
{{selectedValue}}
</body>
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 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