J21042
J21042

Reputation: 1284

Angular ng-repeat pass parameter to href link

I have an existing grails app, built using GSPs and custom tagLibs. I need to incorporate some new code that uses AngularJS. I am new to AngularJS.

Specifically, I have existing links that were generated with custom tags, such as:

<g:custonSearchLink id="${ent.id}" >

that evaluate to

<a href="fullPath/controllerName/method/X", onclick="jQuery.ajax((type:'POST', url:'fullPath/controllerName/method/X', success:function(data,textStatus){jQuery('tableDiv').html(data);}, error:function(...)){}});return false" >...

where X is the id param. I need to have the ng-repeat generate these links, and pass the "X" param value into the href and ajax url paths.

So I understand that I can just use the nested curly braces " {{}}" to pass the X param from the object into the href string,

<li ng-repeat="obj in myList track by obj.id" >
  <a href="fullPath/controllerName/method/{{obj.id}}"

but the onclick ajax url is nested in a single quoted string inside the onclick string. How can I pass the "X" param into that? This does not work:

onclick="jQuery.ajax((type:'POST', url:'fullPath/controllerName/method/{{obj.id}}', 

Note that the "fullPath" in my case is "https://localhost:8453/" since the server that is responding to the AJAX call is running on a different port than the server hosting the GSP.

Upvotes: 1

Views: 13168

Answers (2)

awimley
awimley

Reputation: 712

Using ng-href and ng-click allows you to use AngularJS scope variables in javascript event handlers. Like so:

<div ng-repeat="someItem in list track by someItem.id">
  <a ng-href="/your/url/to/this/id/{{ someItem.id }}"></a>
  <button ng-click="$scope.someAction(someItem.id)"></button>
</div>

So your specific click event handler would be:

ng-click="jQuery.ajax((type:'POST', url:'fullPath/controllerName/method/{{obj.id}}'"

As mentioned by Shashi, you can fire the HTTP request in a scope function, though the way you are currently handling this with inline AJAX should work.

Upvotes: 3

Shashi
Shashi

Reputation: 1182

In this case you can use ng-click

and define a javascript function in your angular controller in the same scope and invoke ajax using $http provider.

<a ng-click="invoke(obj.id)" />

$scope.invoke = function(id){
   $http({
          method:'POST', 
          url:fullPath/controllerName/method/id
        });
}

Upvotes: 1

Related Questions