0

I need angularjs controller to read hidden input field on a form. I tried to define a scope variable in the controller 'postData.TransactionId' and look at this in the controller. But the value is coming as blank. Is it because DOM is not loaded yet for angularjs controller to look at the input field? Are there any alternatives? Thank you!

<form name="form1" id="form1" ng-controller="Ctrl">
    <input type="hidden" id="TransactionId" name="TransactionId" value="@Request.Form["TransactionId"]" ng-model="postData.TransactionId">
</form>

I am trying to inject a service in the script tag of the view but I get an error saying "angular is undefined". Is it possible to read the value in Ctrl this way?

<div ng-controller="Ctrl">
</div>

<script src="~/Scripts/angular-idle.min.js"></script>
<script>

    var app = angular.module('pay', []);
    app.service("PostService", function () {
        this.TransactionID = "Test";
    });
</script>
Jyina
  • 2,530
  • 9
  • 42
  • 80
  • You can use page life hooks in angular . start you operation in $onInit . https://blog.thoughtram.io/angularjs/2016/03/29/exploring-angular-1.5-lifecycle-hooks.html I hope it helps – rahul tiwari Feb 22 '19 at 20:50
  • This is not possible with a hidden input. `ngModel` does not do binding with hidden inputs – Pop-A-Stash Feb 22 '19 at 21:22
  • Maybe `$element` is what you are looking for? – Sagie Feb 23 '19 at 14:49
  • 1
    Possible duplicate of [Angularjs: Get element in controller](https://stackoverflow.com/questions/21311401/angularjs-get-element-in-controller) – Sagie Feb 23 '19 at 14:54

1 Answers1

0

You could try using ng-init to fill the model

<input type="hidden" id="TransactionId" name="TransactionId" value="@Request.Form["TransactionId"]" ng-model="postData.TransactionId" ng-init="postData.TransactionId=@Request.Form["TransactionId"]">

or you could use input type="text" with display style none link

malibeg
  • 2,237
  • 2
  • 17
  • 21
  • I tried to define input elements as suggested but it did not work for me. I think my problem is that controller is invoked first before DOM is loaded. So the controller is still showing blank value in the model postData.TransactionId. Thank you. – Jyina Feb 25 '19 at 15:40
  • I am trying to pass the values to angular service and read them in the controller. But I get an error "angular is undefined". – Jyina Feb 25 '19 at 18:57