Banana Banana - 1 year ago 65
AngularJS Question

Pass Signed In user name to AngularJS controller using model binding

I am trying to pass the signed in user name in the application to an angular controller. I am already passing other parameters using model-binding like this and works perfectly

<input class="form-control" type="text" id="argOne" name="argOne" ng-model="viewModel.test.argumentOne" />

I tried passing the user name using a hidden input but I get an undefined value on the controller

<input class="form-control" type="hidden" id="argTwo" name="argTwo" ng-model="viewModel.test.argumentTwo" value=@UserManager.GetUserName(User) />

I've seen similar examples here, but nothing specific when getting a value directly from the UserManager class from ASP.NET core

Update: I am not asking how to display the Signed in user, the question is how can I pass that value to the angular controller using model binding like shown in the first line of code on the question, but with a hidden field or something similar that the user can't see

Answer Source

According to what you want to do, I'd suggest you to use scope variables to keep the username rather than keeping it in a hidden field. As what you want to keep is a username I'm assuming that you may need to use it in various controller throughout your angularjs app. So I'd rather keep it in application scope to take advantage of scope inheritance.

So What I'm suggesting looks like this :

In the HTML, you assign the username to the pertinent scope variable $rootScope.username :

<html ng-app="myApp" ng-init="$rootScope.username='@UserManager.GetUserName(User)'">
<div ng-controller="myController">
    Your Username is : {{$rootScope.username}}

I the JS you can use it everywhere:

var app = angular.module('myApp',[]);
// you can use $scope.username in this code and it would be inherited from the $rootScope.username
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download