Reputation: 315
Does someone know how to do this simple thing : get a value from a hidden input field with angularjs ? Googled a lot without real success... C# in server side writes a product id, and I need to retrieve it to pass it to my angularjs json service.
Thanx a million times if you're able to answer!
Upvotes: 2
Views: 3776
Reputation: 723
A small enhancement to @Rod Hartzell solutions
var hiddenField = new HtmlInputHidden {Value = "myValue", ID = "hiddenfield" ClientIDMode = ClientIDMode.Static};
hiddenField.Attributes.Add("ng-model","myhiddenfield");
myDiv.Controls.Add(hiddenField);
and
$scope.myTest = $('#hiddenfield').val();
I've set the ClientIdMode to Static (https://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode%28v=vs.110%29.aspx). This way the ClientID value is set to the value of the ID property.
Hope that helps.
Upvotes: 1
Reputation: 440
@Rob Jacobs has the right approach. Essentially this:
$scope.myHiddenElement = $("#ctl00_cphMainContent_hConsentDisagree").val();
Where your hidden element is:
<asp:HiddenField ID="hConsentDisagree" runat="server">
Or...
<input type='hidden' id='ctl00_cphMainContent_hConsentDisagree' value='whatever' />
EDIT To Avoid breaking the spirit of AngularJs you could change the ASP.NET piece to something like this:
var hiddenField = new HtmlInputHidden();
hiddenField.Value = "myValue";
hiddenField.Attributes["ng-model"] = "my-hidden-field";
then it's just this in the controller:
$scope.my-hidden-field
EDIT Number 2
var hiddenField = new HtmlInputHidden {Value = "myValue", ID = "hiddenfield"};
hiddenField.Attributes.Add("ng-model","myhiddenfield");
myDiv.Controls.Add(hiddenField);
Does not seem to work... However this does:
$scope.myTest = $('#MainContent_hiddenfield').val();
Yeah... I know, it breaks the spirit of Angular but... sometimes you gotta just make it work. I don't have a better answer.
Upvotes: 1
Reputation: 6629
This is how I do it:
@functions{
public string GetAntiForgeryToken()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
<input id="antiForgeryToken" type="hidden" value="@GetAntiForgeryToken()" />
var antiForgeryToken = $("#antiForgeryToken").val();
EDIT
Without jQuery:
var antiForgeryToken = document.getElementById("antiForgeryToken").value;
Using the angular $document:
var antiForgeryToken = $document.find("#antiForgeryToken").val();
Upvotes: 3
Reputation: 910
You can try generating ng-model="hiddenValue"
attribute on the field from server side and then try to get the value in your controller with $scope.hiddenValue
. Of course the hidden field should be in the the scope of the controller.
Upvotes: 0