How to get current user from sails into an angular view - angularjs

I have gotten a list of users from my sails back end into an angular view using $http. However, all I need is the information of the current user, and I need to access each attribute individually. Can someone provide for me an example of how I might go about this?

In api/controllers/UserController.js. This sails function returns the current user information in req.user.
module.exports = {
getUser: function(req,res) {
return res.send(req.user);
};
In config/routes.js. This is the route to the 'getUser' function in UserController.js.
'/getUser': {
controller: 'UserController',
action: 'getUser'
}
In assets/js/controllers.js, here is the $http request to the 'getUser' function in UserController.js. This is how you get the information from req.user into the front end.
angular.module('myApp.controllers', []).
controller('myCtrl', ['$scope', '$http', function($scope, $http) {
$http.get("http://localhost:1337/user/getUser").then(function(result) {
$scope.currentUser = result.data;
})
}]);
In assets/js/app.js, make sure your angular route is set to your view.
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view', {templateUrl: 'partials/view.html', controller: 'myCtrl'});
}]);
After putting this code (with your own variables/routes/server info) in the correct places, you can access the current user in your view like this
<div ng-controller="myCtrl">
{{ currentUser.email }} <br>
{{ currentUser.username }} <br>
{{ currentUser.etc }}
</div>
I searched the internet high and low for a week for an answer on how to do this and eventually came up with this. I see that a lot of people (on this site especially) have asked the same question, and I never really found a good, explicit answer. So I thought I would post what I've come up with as an answer to my own question.

Related

AngularJs - Unable to pass object using routeProvider

I load some data from the server, and then update the view using ng-repeat. The user has the ability to edit the data in another page. Now, is the part where I'm a bit confused. I can pass some parameters using $routeProvided combined with $routeParams, lets say id and fetch the data again from the server depending on that id. I believe there's a better way, something like passing the whole object to the next controller, rather than conducting another call the server. That's what I've got working right now:
app.config(function($routeProvider) {
$routeProvider
.when('/editPost/:postId/:author', {
templateUrl: 'editPost.html',
controller: 'editPostCtrl'
});
});
app.controller('editPostCtrl', function($scope, $routeParams) {
console.log($routeParams.author + ", " + $routeParams.postId);
});
Now, I cant extract the object with the following code:
HTML:
<div ng-repeat="post in posts">
<button class="btn" ng-click="editPost(post)">Edit</button>
</div>
JS:
app.config(function($routeProvider) {
$routeProvider
.when('/editPost/:post', {
templateUrl : 'editPost.html',
controller : 'editPostCtrl'
});
});
app.controller('editPostCtrl', function($scope, $routeParams) {
console.log($routeParams.post); //results in [object object]
});
Is there a better way for achieving this?

Reading URL Query string

I have the following URL:
http://myUrl.com/#/chooseStyle?imgUpload=6_1405794123.jpg
I want to read the imgUpload value in the query string - I'm trying:
alert($location.search().imgUpload);
But nothing alerts, not even a blank alert - but console reads:
$location is not defined
I need this value to add into a controller to pull back data, and also to carry into the view itself as part of a ng-src
Is there anything I'm doing wrong? this is my app config:
capApp.config(function($locationProvider, $routeProvider) {
$locationProvider.html5Mode(false);
$routeProvider
// route for the home page
.when('/', {
templateUrl : '/views/home.html',
controller : 'mainController'
})
// route for the caption it page
.when('/capIt', {
templateUrl : '/views/capIt.html',
controller : 'mainController'
});
}):
This is the view:
<div class="container text-center">
<h1 class="whiteTextShadow text-center top70">Choose your photo</h1>
</div>
<script>
alert($location.search().imgUpload);
</script>
Main controller:
capApp.controller('mainController', function($scope) {
$scope.message = 'Whoop it works!';
});
My end goal is that I can find a solution to capturing and re-using data from the query string.
I will also mention, this is only my first week in Angular, loving it so far! A lot to learn...
<script>
alert($location.search().imgUpload);
</script>
You're making two mistakes here:
executing code while the page is loading, and the angular application is thus not started yet
assuming $location is a global variable. It's not. It's an angular service that must be injected into your controller (or any other angular component). This should cause an exception to be thrown and displayed in your console. Leave your console open always, and don't ignore exception being thrown.
You should not do this
<script>
alert($location.search().imgUpload);
</script>
// you need to inject the module $location
//(either in service, or controller or wherever you want to use it)
// if you want to use their APIs
capApp.controller('mainController', function($scope, $location) {
$scope.message = 'Whoop it works!';
//use API of $location
alert($location.search().imgUpload);
});

ngGrid not displayed when used with route provider

Below is my HTML and the code to do a web service call and display the data in ngGrid. The problem is with the route provider, I'm not being able to show the grid in my separate view, but if I do the exact same code without the route provider,and load just that page, it works perfectly fine.
Since I'm very new to angularJS, any suggestions would be appreciated.I've done lot of research but did not work, at least for me. Please consider this if I have missed related post somewhere. Thanks ahead!
<div>
<!--Placeholder for views-->
<div ng-view=""></div>
</div>
//this is what I have in one of my view for grid.
<div class="gridStyle" data-ng-grid="gridOptions">
</div>
/* display/get/call the JSON data from the web service and bind it to the view */
var app = angular.module('salesApp',['ngGrid']);
app.config (['$routeProvider', function ($routeProvider){
$routeProvider
.when('/sales',
{
controller:'salesCtrl',
templateUrl:'Partials/sales.html'
})
.when('/associate',
{
controller:'assocCtrl',
templateUrl:'Partials/associate.html'
})
.otherwise({redirectTo:'/sales'});
}]);
app.controller('salesCtrl', function($scope, $http) {
$http.jsonp('http://some url...')
.success(function (data) {
$scope.sales = data;
});
$scope.gridOptions = {data: 'sales',
columnDefs:[{field:'Region_Num', displayName: 'Region Num'}
],
showGroupPanel: true
};
});
This is an older post; but I was having the same problem. It turns out when I defined the app/Moduile; I was not passing ngGrid in as one of the options:
myApp = angular.module('myApp', ['ngGrid']);
That is clearly not your problem; as I do see the statement in your code; so this answer is probably for other people who find this question via Google.

Angular best way to handle email confirm route

I'm trying to work out the best way to define a route that users will click on in the confirmation email that they receive.
I have defined a path like this.
app.config(function ($routeProvider, $locationProvider, $httpProvider) {
$routeProvider.when('/app/setup/confirm/:code',{
// code is $routeParams.code
});
});
What needs to happen is:
Make a $http call to the api resource that logs the code as being
clicked and confirms email address
Log the user in for both the api and front end
Return the user to the next step of the setup process now their email is confirmed.
If the code is bogus and the $http call returns false then redirect them to the signup page.
As this route doesn't need a template, I can't work out where to put the code to do this. If I only defined a controller it never gets instantiated until I also define a template??
For example this works
app.config(function ($routeProvider, $locationProvider, $httpProvider) {
$routeProvider.when('/app/setup/confirm/:code',{
controller: function($routeParams){
console.log($routeParams.code);
},
template: function(){
return '<html></html>';
}
});
});
But as soon as I remove the template or even return an empty string in the template the controller doesn't work. There must be right way to do this and this doesn't feel like it.
Can anyone give me a pointer? I'm using v1.1.2. Thanks!
You should be able to resolve the request to a controller without specifying the template. Try this pattern:
app.factory('myService', function () {
return 1;
});
app.controller('MyCtrl', function ($scope, myService) {
console.log(myService);
});
app.config(function ($routeProvider) {
$routeProvider.when('/app/setup/confirm/:code', {
resolve: {
redirect: 'MainCtrl'
}
});
})

Angular JS / data handling / overview page

I´m developing an Angular-App. The user has to enter data on different pages whereas it´s possible to switch between the pages. Furthermore there is an "overview page" where the user can see the entered data.
So now im thinking about how to show the entered data on the overview page. Should i just use $rootScope to get the data or is it better to store it in JSON-objects or - but this is not suggested by Angular - store data in a service?
So where to get the entered data from the different pages?
Thanks!
If you want to persist data between actual HTML pages and not routes within a single page, you could use LocalStorage. Here is a service that will make that a little easier.
Another approach would be to use cookies. You can read more about using cookies in Angular here.
If you are wanting to persist the data across different routes, you will need to create a shared service. Here is an example of such an approach:
<div ng-app="myApp">
one | two
<div ng-view></div>
<script id="one.html" type="text/ng-template"><div><h1>Template One</h1>foo = {{shared.foo}}</div></script>
<script id="two.html" type="text/ng-template"><div><h1>Template Two</h1>foo = {{shared.foo}}</div></script>
</div>
angular.module('myApp', []).
config(function($routeProvider){
$routeProvider.
when('/one', {templateUrl: 'one.html', controller: 'OneCrtl'}).
when('/two', {templateUrl: 'two.html', controller: 'TwoCrtl'}).
otherwise({redirectTo: '/one'});
}).
service('sharedService', [function() {
this.foo = 'bar';
}]).
controller('OneCrtl', function($scope, sharedService){
$scope.shared = sharedService
}).
controller('TwoCrtl', function($scope, sharedService){
$scope.shared = sharedService
});
Here's a fiddle.

Resources