This is the first time i am using Angular.js. So my workflow could be wrong.
How do i pass data from controller to the view
ng-view -> Displays html page using jade
When user clicks on submit button, i use $http on the controller and submit the request to the server.
The server returns me the necessary data back which i need to pass to another view.
My code snippet
function TrackController($scope,$http,$location,MessageFactory){
$scope.message = MessageFactory.contactMessage();
$scope.submit = function () {
var FormData = {
'track_applicationid': $scope.track_applicationid,
'track_email': $scope.track_email
}
$http({method: 'POST', url: '/track', data: FormData}).
success(function(data, status, headers, config) {
$scope.registeredDate = 'data.REGISTERED_DATE';
$scope.filedDate = data.FILED_DATE;
$location.path('trackMessage');
}).
error(function(data, status, headers, config) {
console.log('error');
});
}
}
In the above code, i want to pass registeredDate and filedDate to trackMessage view.
After going through the comments, i understood you are using one controller for two views.
If you want to set values to $scope.registeredDate and $scope.filedDate, You have to declare those objects globally using root-scope(Not recommended) or
use Angular values.
I recommended to use two different controllers.
Related
I was updating my view by refreshing the page. I know that there is a better way. Can someone show me how to update the view data without refreshing the page:
myApp.service("deleteService", function ($http) {
this.removeRow = function (recId, compName, custName, docName) {
$http.post('DeleteRecord', { settingID: recId,companyName: compName,customerName: custName, documentName: docName } )
.success(function (data, status, headers, config) {
window.location.reload();
})
.error(function (data, status, header, config) {
});
}
});
Without seeing the rest of your code it is hard to be able to give you an exact answer, but I'm going to assume you have a service to get your data.
Approach 1) You can inject your "getService"? into this service and access the function you use to retrieve the data initially.
Approach 2) Instead of having a seperate service for each CRUD function, you can have a CRUD service that will manage the data manipulation, this way you can just call the "get" function without injecting a seperate service.
I am starting to build a web application.
The user can select and add items to a list of fruit. The list of fruit objects is stored in an array in Javascript/AngularJS.
When the user presses the Submit button, I want the entire list of fruit to be sent to the server, where the list is then saved into a database.
I have only a basic understanding of HTTP. Would I want to POST the array? How would I do this?
I'd prefer you to go for $resource which includes in ngResource module.
While passing array inside your post call you need to mention isArray option to true inside $resource option
CODE
angular.module('app',[])
//factory will have resource object
.factory('myService',function($resource){
var postFruitData = function(){
return $resource('/savefruit', {}, {saveData: {method:'POST', isArray: true}});
}
return{
saveData: postFruitData
}
})
.controller('mainCtrl',function($scope,myService){
//this function needs to be call on post like form ng-submit
$scope.postFruitData = function(){
myService.saveData({}, $scope.data).$promise.then(function(data){
//you will get data here
});
}
});
For more info you can also take look at this SO Question
Hope this could help you. Thanks.
Here's a POST example that posts an array of fruit to the server. This code would be located inside your button click function.
$scope.fruit = [{name: 'Apple'}, {name: 'Grape'}];
// Simple POST request example (passing data) :
$http.post('/someUrl', {fruit: $scope.fruit}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Take a look at the angular documentation for $http. This should help you out.
I trying to pass a form via $http.post from AngularJS to Sailsjs
My Sails Controller
create: function(req, res) {
console.log("req: "+req.param('user.firstName'));
res.send(req.param('user.firstName'));
},
My Angular Controller
function RegisterController($scope, $http) {
$scope.submit = function(){
console.log($scope.user.firstName); // works fine so far
$http.post('/user/create', $scope.user)
.success(function(data, status, headers, config) {
console.log("success");
})
.error(function(data, status, headers, config) {
console.log("error");
});
}
}
If I call my sails function like so /user/create?user.firstName=myFirstName its works fine. But if I try to read my passed data if I pass from angular. I don't know. I can't read the parm...
Someone any idea or a small example?
Cheers awesome community =)
You're posting the $scope.user object to your route, so it won't be namespaced under user. If the $scope.user contains, for example:
{firstName: "John", lastName: "Doe"}
then they would be available in your controller action as req.param('firstName') and req.param('lastName').
If you were to post the entire $scope object to /user/create (don't do this!), then you would be able to access req.param('user').firstName, req.param('user').lastName, etc. You still wouldn't be able to access things like req.param('user.firstName'), though; those are Angular expressions but they don't work server-side.
Assume I have a directive that contains a form where a user can enter in the name of a fruit.
I have a FruitFindController. User enters fruit name, "Apple", clicks a button which submits to controller.
Controller calls a service "GetFruitInfo(fruit)" and passes in "Apple" as parameter.
Once the information is received, it should call a method "addToListAndDoStuff()" in order to add the fruitinfo to the list.
My issue is, in my FruitFindController (assume fruitFinder is the service)...
$scope.GetFruitInfo = function() {
$scope.foundFruit = fruitFinder.GetFruitInfo($scope.fruitField);
// should alert "Found Fruit" and call addToListAndDoStuff() method to add the foundFruit information to the list managed by another directive, "FruitList".
}
What is the best way to "wait for the information is stored into $scope.foundFruit before doing any code below and popping up the alert box?
The best way is to use a promise. In your fruitFinder service, the GetFruitInfo method would look something like this..
function GetFruitInfo(fruit) {
var delay = $q.defer();
$http({method: 'GET', url: 'http://myapi.com/getFruitInfo?fruit=' + fruit}).
success(function(data, status, headers, config) {
delay.resolve(data);
}).
error(function(data, status, headers, config) {
delay.reject(data);
});
return delay.promise;
}
This method returns a promise object that you can wait for it to resolve in your controller using the .then() method, like this..
$scope.GetFruitInfo = function() {
$scope.foundFruit = fruitFinder.GetFruitInfo($scope.fruitField).then(function(response) {
alert('Found Fruit');
addToListAndDoStuff(response);
});
}
I have have spent hours trying all of the different methods given online but nothing works. I just simply want to load a script to run after all images have loaded. Is there something about Angular that won't allow me to do this? I'm using $routeProvider:
var photos = {
name: 'photos',
url: '/photos',
views: {
main: {
templateUrl: "views/photos/photos.html",
controller: function($scope,$http){
$http({
url: 'get/photos',
method: "POST"
})
.success(function (data, status, headers, config) {
$scope.data = data;
// this doesn't work
$(window).load(function() {
myScript();
});
})
.error(function (data, status, headers, config) { $scope.status = status; });
}
}
}
};
By the way, I'm not getting any errors in the console.
It seems to me that the http POST call retrieves the photos. And I am suppose that myScript is a function. So why not try this:
var photos = {
name: 'photos',
url: '/photos',
views: {
main: {
templateUrl: "views/photos/photos.html",
controller: function($scope,$http){
$http({
url: 'get/photos',
method: "POST"
})
.success(function (data, status, headers, config) {
$scope.data = data;
myScript();
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
}
}
}
};
since the myScript function only runs after the POST succeeds. I am supposing that the data refers to the actual image data.
I don't know if I really understood what type of data you are trying to get, but I think you could try with promises
$http in Angular already return a promise wrapped in .success or .error, but you can also use the .then() callback like with every other promise
So if the problem is to wait for the success() callback to be finished you could do something this way, replacing it by several then() :
$http.post(...).then(
//function which will wait for the data to be downloaded
//here you can alter data, check some values etc...
).then(
//the script for what you want after
myScript();
);
I made a little fiddle to explain : http://jsfiddle.net/Kh2sa/2/
It simulates a long response time with $timeout, so you have to wait 3 secondes to see your modified data, which remains in its initial state until you call the myScript() function
AFAIK, Angular does not provide a way to inform us when images have finished loading.
You will need to write your own directive for this. The directive would wrap the necessary JavaScript/jQuery code that would detect the finished loading condition for one or more images.
jQuery callback on image load (even when the image is cached) and https://github.com/desandro/imagesloaded might help.