Angular way to get a value of a hidden element for use in a controller

24,305 views
Skip to first unread message

kenneth...@gmail.com

unread,
Nov 13, 2012, 5:10:50 PM11/13/12
to ang...@googlegroups.com
<div ng-controller='FooCtrl'>
<input id='x' type='hidden' name='token' ng-model='token' value='asodif2321870wpeoifjas'/>
</div>

Suppose the above is generated by the server.

function FooCtrl($scope{
    $scope.token
}

How do I set this up correctly so that FooCtrl has access to the hidden input value?



Peter Bacon Darwin

unread,
Nov 13, 2012, 5:49:23 PM11/13/12
to ang...@googlegroups.com
Hidden elements are not really supported by AngularJS.  What is your use case?

--
You received this message because you are subscribed to the Google Groups "AngularJS" group.
To post to this group, send email to ang...@googlegroups.com.
To unsubscribe from this group, send email to angular+u...@googlegroups.com.
Visit this group at http://groups.google.com/group/angular?hl=en.
 
 

Michael Bielski

unread,
Nov 13, 2012, 6:24:54 PM11/13/12
to ang...@googlegroups.com
Why not? It's just another form control on the page. I've done this in a couple of places and haven't had any problems with it. Now I did set the value of the hidden field to what I wanted it to be in the controller, so maybe that is the difference?

function FooCtrl($scope{
    $scope.token = "blah";

     $scope.changeToken = function(){
          $scope.token = "blah blah":
     }
}

Peter Bacon Darwin

unread,
Nov 13, 2012, 6:43:08 PM11/13/12
to ang...@googlegroups.com
OK, so I was being lazy.  The trouble is that Angular will not read the value set by the server into the ng-model value and vice versa.


     }
}

--

Ken Koontz

unread,
Nov 13, 2012, 7:01:46 PM11/13/12
to ang...@googlegroups.com
Peter, Michael, thanks for your responses.

The token is a value needed to perform requests against the server something like this:

http://example.com/foo?token=2p9834hdaioj

On the initial page load before angular linking or compiling, the value of the input field is prepopulated in the html coming from the server.

Any subsequent request to example.com needs this token as a key.

Perhaps I'm designing it wrong.

jpl

unread,
Nov 13, 2012, 7:02:31 PM11/13/12
to ang...@googlegroups.com
hey,

what is the best way of getting such data across then ?

say I want part of my page rendered serverside and extend upon that with angular. So some part of the model needs to get filled/hooked with what is already there,
is the only possibility and ajax type call immediately after the page is loaded to fill in the controller's model ?

sorry I'm new to angular and trying to figure out the best possible work flow..

thanks

Michael Bielski

unread,
Nov 13, 2012, 7:38:11 PM11/13/12
to ang...@googlegroups.com, kenneth...@gmail.com
Well, like I said, I take a value that is given me from the server and set it to that model value. When I do my post, the value is there. The problem with a hidden field is that if you change the value programmatically, you MUST change it via the $scope or the new value will not get picked up.

If you have a token that must be sent back and forth, perhaps a cookie would be a better place for it? I use a cookie in my app and everything is fine. You could also pass that value in a custom header. You just have to remember to tell the script to pass that header on every trip to the server.

var WL = $http({ method: "GET", url: "your/url/here", headers: { "MyAuth": $scope.token} });

(I tend to do my trips to the server with $http because $resource has a documented problem with custom headers. If you use cookies you can use $resource very effectively.)

Tony Polinelli

unread,
Nov 13, 2012, 8:04:36 PM11/13/12
to ang...@googlegroups.com
would ng-init help ?   I was just thinking about this kind of issue myself: 





--
You received this message because you are subscribed to the Google Groups "AngularJS" group.
To post to this group, send email to ang...@googlegroups.com.
To unsubscribe from this group, send email to angular+u...@googlegroups.com.
Visit this group at http://groups.google.com/group/angular?hl=en.
 
 



--
Tony Polinelli
http://touchmypixel.com

zdam

unread,
Nov 13, 2012, 8:29:54 PM11/13/12
to ang...@googlegroups.com, jo.p...@gmail.com
I use this simple directive to allow me to have data that is populated by the server (asp.net mvc views)
marshalled into the appropriate model property in Angular: 

    .directive('mpValueCopy', function($parse) {
        return function(scope, element, attrs) {
            if (attrs.ngModel) {

                if (element[0].type == "radio") {
                    if (element[0].checked == true) {
                        $parse(attrs.ngModel).assign(scope, element.val());
                    }
                } else {
                    $parse(attrs.ngModel).assign(scope, element.val());
                }
            }
        };
    })


Example Usage:

<input type="hidden" ng-model="RegistrationDate" value="<%=Model.RegistrationDate %>" mp-value-copy/>

<input type="text" ng-model="UserName" value="<%= Model.UserName %>" mp-value-copy/>

Cheers, Adam.

Ken Koontz

unread,
Nov 14, 2012, 1:04:06 AM11/14/12
to ang...@googlegroups.com, jo.p...@gmail.com
@zdam. Thanks for the directive. This appears like something that would work. However, I can't seem to get it running. I have the following and I still get undefined in the console.log

markup (jade):
input(type='hidden', ng-model='token', value='#{token}', copy-value)

app.js:
var dwibbles = angular.module('dwibbles', []);

dwibbles.directive('copyValue', function($parse) {
  return function(scope, element, attrs) {
    if (attrs.ngModel) {
      if (element[0].type === "hidden") {
        $parse(attrs.ngModel).assign(scope, element.val());
      }   
    }   
  };  
})

var ProfileCtrl = function($scope, $http) {
  console.log($scope.token);
};

zdam

unread,
Nov 14, 2012, 2:18:13 AM11/14/12
to ang...@googlegroups.com, jo.p...@gmail.com, kenneth...@gmail.com

I'm not exactly sure what your value='#{token}' means, I assume that is replace on the server side by something real?

Anyway, here is a fiddle that works, note the value is set to something. ie. the server has sent html across the wire to the browser with the value already set.

Ken Koontz

unread,
Nov 14, 2012, 2:25:48 AM11/14/12
to zdam, ang...@googlegroups.com, jo.p...@gmail.com
@zdam. #{token} is jade string interpolation. Thanks for the fiddle!

Peter Bacon Darwin

unread,
Nov 14, 2012, 4:13:00 AM11/14/12
to ang...@googlegroups.com
Personally I would use ng-init to push data to the scope from the server but Adam's mp-value-copy also works.  Remember that neither of these put changes to the values on scope back into the value of the hidden input.

Michael Bielski

unread,
Nov 14, 2012, 11:06:13 AM11/14/12
to ang...@googlegroups.com, jo.p...@gmail.com, kenneth...@gmail.com
Oh... are you trying to get the value of the hidden field by accessing the value attribute of it? That's won't work. You need to get the value of the $scope variable, in your case "token". That's why I set it in the controller as a pre-defined value.

taurus...@gmail.com

unread,
Nov 29, 2012, 11:12:38 PM11/29/12
to ang...@googlegroups.com, kenneth...@gmail.com
I'm using angularjs with Rails and needed to server-side data into a controller. I was also thrown by the 'toy app' warning in the ngInit docs. 

To solve this, I added a data attribute to the root element of my app and set it to the value from the server. I then used the $rootElement service to access that attribute in my angularjs controller.

Your markup might look like this (note data attributes should be prefixed with 'data-'):
...
<div ng-app ng-controller="someController" data-some-object-id="12345">
</div>
...

And, in your controller:

function someController($scope, $rootElement) {
  alert($rootElement.data('some-object-id'));
}

Voila!

Note: Use cases involving passing more than 1 or 2 data values into a controller probably calls for some sort of service...

Hope that helps,

Taurus

Justin Zollars

unread,
Jul 6, 2013, 3:29:07 PM7/6/13
to ang...@googlegroups.com
Defense against cross site scripting!
Reply all
Reply to author
Forward
0 new messages