Pass datas between routes angularjs/expressjs - javascript

I have a form, and when I submit it, another form is displayed with radio buttons which are other datas. I select one and submit it. I want the data to be displayed in another page but it doesn't display anything with what I've done.
So there is the /form route, and I want to be redirect on the /confirmation route with my datas after the last submit.
Bellow is my formController in angularjs
.controller('formController', ['$scope', '$http', '$location', function($scope, $http, $location) {
$scope.pageClass = 'form';
$scope.firstName = '';
$scope.lastName = '';
$scope.email = '';
$scope.departure = '';
$scope.destination = '';
$scope.submitFirstForm = function() {
$http.post('/form', {
firstName: $scope.firstName,
lastName: $scope.lastName,
email: $scope.email,
departure: $scope.departure,
destination: $scope.destination,
}).then(function(res) {
$scope.response = res.data;
});
}
$scope.submitConfirmationForm = function(flight){
$http.post('/confirmation', {
departure: $scope.departure,
destination: $scope.destination
}).then(function(res) {
$scope.otherResponse = res.data;
$location.path("/confirmation");
});
};
}]);
Bellow is my express post function only for the /CONFIRMATION route
app.post("/confirmation",function(req,res)
{
var departure=req.body.departure;
var destination=req.body.destination;
otherResponse = {
"confirmation": [{
"departure": departure,
"destination": destination,
"msg": "MSG OK",
}]
};
res.json(otherResponse);
});
Finally, bellow my confirmation.html to see what is going on with my json otherReponse
<pre>
{{otherResponse | json}}
</pre>

You are not passing the 'value', you need to do something like this:
$location.path('/confirm/').search({param: 'otherResponse'});
$location methods are chainable.
this produce :
/confirm/?param=otherResponse
Check the doc for $location

Related

API, angularJS, to get datas

I never done angularJS from all my life and i am lost.
So i have done this file, to obtain datas from an api with a filter of time.
forecast.js
(function() {
angular.module('application').factory('Forecast', ['$http', '$q', function($http, $q){
var ApiAddr = "api.com/";
forecast.getResults = function(timeStart, timeEnd){
// We map application varaible names with API param names
var httpParams = {
type: "global",
time: "minute",
tsmin: timeStart,
tsmax: timeEnd
};
return $http.get(apiAddr, {
params: httpParams,
cache: true
}).then(function(data){
return data;
},
function(response){
console.log(
"HTTP request "+ApiAddr+
" (with parameters tsmin="+httpParams.tsmin+", tsmax="+httpParams.tsmax+
", type="+httpParams.type+", time="+httpParams.time+
(httpParams.motive ? ", motive="+httpParams.motive : "")+
(httpParams.vector ? ", vector="+httpParams.vector : "")+
(httpParams.media ? ", media="+httpParams.media : "")+
") failed with "+response.status
);
return $q.reject(response);
}
);
}];
But i have no idea to make a controller adapter to this. What type of controller i can do ?
Every exemple are based on a fixed json file, with no parameters.
Moreover, i want, in HTML to imput the time filter, but i have totaly no idea of what to do for this. The example i have seen were to get datas, no to send.
Ps : I have made 2 days of research about this, i have never done front end programming in my life.
(function() {
angular.module('application', [])
.factory('Forecast', ['$http', '$q', function($http, $q) {
var apiaddress = 'api.com';
var forecast = {};
forecast.getResults = function(timeStart, timeEnd) {
// We map application varaible names with API param names
var httpParams = {
type: "global",
time: "minute",
tsmin: timeStart,
tsmax: timeEnd
};
return $http.get(apiaddress, {
params: httpParams,
cache: true
}).then(function(result) {
return result.data;
});
};
return forecast;
}])
.controller('SampleCtrl', ['$scope', 'Forecast', function($scope, Forecast) {
$scope.forecastReport = '';
$scope.getForecast = function() {
Forecast.getResults($scope.timeStart, $scope.timeEnd)
.then(function(report) {
$scope.result = report;
}).catch(function(err) {
$scope.result = '';
console.error('Unable to fetch forecast report: ' + err);
});
};
}]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="application" ng-controller="SampleCtrl">
<label>Time Start:
<input type="text" ng-model="timeStart"/></label>
<label>Time End:
<input type="text" ng-model="timeEnd"/></label>
<button ng-click="getForecast()">Get Forecast</button>
<hr/>
<div>
<b>Forecast Result:</b>
</div>
<pre>{{forecastReport | json}}</pre>
</div>
Just inject the factory into your controller like this:
var app = angular.module('application');
app.controller('myController',
['$scope', 'Forecast', function($scope, Forecast) { /* access to Forecast*/}]);
Or with a component (cleaner):
app.component('myComponentCtrl', {
templateUrl: 'template.html'
controller: myComponentCtrl
})
myComponentCtrl.$inject = ['$scope', 'Forecast'];
function myComponentCtrl($scope, Forecast) {/* ... */ }

watch and apply changes to object in angular js service

i am trying to change and apply the value of an object in an angular js service.
i have been able to successfully watch the object and i saw the changes but i cannot apply it to take effect .
i am changing the value from my login controller .
i am watching the $rootScope.userobject and would want to apply changes immediately to $rootScope.userobj as it used in my service for some important stuff but it doesn't seem to apply . what am i doing wrong . see my code below
MyApp.angular.factory('appService', function ($rootScope, $timeout) {
$rootScope.userobject = localStorage.getItem('userdataconfig');
$rootScope.userobj = JSON.parse($rootScope.userobject);
if(!rootScope.userobj){
$rootScope.userobj = {};
}
$rootScope.$watchCollection('userobject', function(newvalue, oldvalue)
{
$timeout(function(){
$rootScope.userobject = newvalue;
$rootScope.userobj = JSON.parse($rootScope.userobject);// i need this updated value to take effect so i can use it in my userconfig below
});
}, true);
return {
userconfig: {token: $rootScope.userobj.token, id: $rootScope.userobj.id, username: "josieboy", fullname: $rootScope.userobj.name, profile_pix: ""}
}
})
MyApp.angular.controller('loginctrl', ['appService', '$scope', '$http', 'InitService', '$rootScope', function (appService, $scope, $http, InitService, $rootScope) {
$scope.loginnow = function()
{
var userdata = { 'id': 3, 'token':'867eb6fcd04b543f97ff6d2c0a64c557', 'name':'Ajose Joshua', 'profile_pix':''};
localStorage.setItem('userdataconfig', JSON.stringify(userdata));
var userobject = localStorage.getItem('userdataconfig');
$rootScope.userobject = userdata;
}
}])

How to empty(or reset) all the input fields on a form after successfull submission in AngularJS in following code?

I've a following controller code with me :
var app = angular.module('app_name');
app.controller("manageUsersController", [ "config", "$scope", "$http", "$mdToast",
function(config, $scope, $http, $mdToast) {
$scope.add = function() {
var userData = {
email : $scope.manageUsers.email,
password : $scope.manageUsers.password,
schoolId : '1',
name : $scope.manageUsers.name,
mobileNumber : $scope.manageUsers.mobileNumber
};
$http.post(config.webServicesUrl.postAddUser, userData, headerConfig).success(
function(data) {
displayToastMessage("User added successfully", $mdToast);
}).error(function(error) {
console.log(error.error);
});
}
}]);
All the HTML fields are input fields and are accessed using $scope object.
I tried with $setPristine but it didn't work.
Somebody please help me in setting all the fields to empty upon successful submission of form only in my code.
Thanks.
If you want to reset your form upon completion, I think you have to reset the $scope.manageUsers object manually once your post request has resolve:
$http.post(config.webServicesUrl.postAddUser, userData, headerConfig).success(
function(data) {
// has I don't know if you have other properties
// I reset each property manually,
// but you could probably do $scope.manageUsers = {}
$scope.manageUsers.email = null;
$scope.manageUsers.password = null;
$scope.manageUsers.name = null;
$scope.manageUsers.mobileNumber = null;
displayToastMessage("User added successfully", $mdToast);
}).error(function(error) {
console.log(error.error);
});
You can use $setPristine() here:
$http.post(config.webServicesUrl.postAddUser, userData, headerConfig).success(
function(data) {
displayToastMessage("User added successfully", $mdToast);
$scope.form.$setPristine(); // <---------here.
}).error(function(error) {
console.log(error.error);
});
Plnkr demo in action.
It should work for you.
$http.post(config.webServicesUrl.postAddUser,userData,headerConfig)
.success(function(data) {
$scope.manageUsers={};
displayToastMessage("User added successfully.", $mdToast);
}).error(function(error) {
console.log(error.error);
});

How to update model using angularjs, Django,Django rest framework

I have such json representation of a post by its id:
http://127.0.0.1:8000/update/1?format=json
{"title": "about me", "content": "I like program", "created": "2014-11-29T18:07:18.173Z", "rating": 1, "id": 1}
I try to update rating by button click:
<button ng-click="click(post.id)">Click me</button>
I have such javascript code:
<script>
var demoApp = angular.module('demoApp',['ngResource']);
demoApp.controller( 'AllPosts', function ($scope, $http)
{
$http.get('/blogpost/?format=json').success(function(data,status,headers,config)
{
$scope.posts = data.results;
$scope.predicate = '-title';
$scope.click = function(post_id, $resource){
var Post = $resource('/update/:PostId ',{PostId:post_id,format:'json'} );
post = Post.get({PostId:post_id}, function() {
post.rating = post.rating+ 1 ;
post.$save();
});
};
}).error(function(data,status,headers,config)
{} )
;})
</script>
Peharps i have mistake because in json i have a single object. But i dont really know
Besides i have such view to have a json by certain post by its id:
class UpdateModel(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'id'
queryset = BlogPost.objects.all()
serializer_class = BlogPostSerializer
permission_classes = (AllowAny,)
A quick tidy up of your script tag shows that you are only defining the function click if the http call was successful.
I would suggest moving the definition of the click method outside of the success callback.
You may also be running into a race condition that the click function has not been defined before clicking the actual button. Regardless you will want to move that function definition to where the controller is actually created.
Suggested edits (moved click definition outside of http call response):
var demoApp = angular.module('demoApp', ['ngResource']);
demoApp.controller('AllPosts', function($scope, $http, $resource) {
$scope.click = function(post_id) {
var Post = $resource('/update/:PostId ', {
PostId: post_id,
salutation: 'json'
});
post = Post.get({
PostId: post_id
}, function() {
post.rating = post.rating + 1;
post.$save();
});
};
$http.get('/blogpost/?format=json').success(function(data, status, headers, config) {
$scope.posts = data.results;
$scope.predicate = '-title';
}).error(function(data, status, headers, config) {});
})
Updates:
Injected $resource into the controller
Removed $resource from click function params

Accessing LinkedIn API from AngularJS

I am building an app with Angular.js accesing the LinkedIn API. What happens is that when I do a call to the API, the model does not get refreshed inmediately, but after I do another change on the screen. For example, I have binded the API call to a button, but I have to press it twice for the screen to get the data refreshed. This is my controller:
angbootApp.controller('AppCtrl', function AppCtrl($scope, $http) {
$scope.getCommitData = function() {
IN.API.Profile("me").fields(
[ "id", "firstName", "lastName", "pictureUrl",
"publicProfileUrl" ]).result(function(result) {
//set the model
$scope.jsondata = result.values[0];
}).error(function(err) {
$scope.error = err;
});
};
});
And this is my button and a link with the content:
<div>
{{jsondata.firstName}}
<form ng-submit="getCommitData()">
<input type="submit" value="Get Data">
</form>
</div>
EDIT: Explanation on how I did it here
You need to call $scope.$apply when retrieving the results/error
angbootApp.controller('AppCtrl', function AppCtrl($scope, $http) {
$scope.getCommitData = function() {
IN.API.Profile("me").fields(
[ "id", "firstName", "lastName", "pictureUrl",
"publicProfileUrl" ]).result(function(result) {
//set the model
$scope.$apply(function() {
$scope.jsondata = result.values[0];
});
}).error(function(err) {
$scope.$apply(function() {
$scope.error = err;
});
});
};
});
Anything outside angular world does not trigger automatic refresh of the views.
See $apply

Categories