问题描述:

I have the following

 <div>

<div ng-repeat="data in datas" title='{{ data.name }}' onClick="location.href='\{{ data.name }}'" >{{ data.name }}</div><br/>

</div>

in my angular file i have

 var mainApp= angular.module('mainApp',[]);

mainApp.controller('formCTR',['$scope','$http',function($scope,$http){

$http.post('/here',{ data: 'something' }).success(

function(data){

$scope.datas=data;

}

)

}]);

when i do the click the url shows

http://localhost:3000/url/{{ data.name }}

how do i display the name of the data inside the onClick to

http://localhost:3000/url/right_name

thanks

网友答案:

If you want to do redirection in angular, you can use either of the 2 steps using 'ng-click' using a click handler or 'ng-href' with a url as below:

<div>
<div ng-repeat="data in datas" title='{{ data.name }}' ng-click="redirect(data.name)" >{{ data.name }}</div><br/>
</div>

and in your controller scope add the redirect function

$scope.redirect = function (route) {
  $location.path('/' + route);
}

This approach allows you to use the same function for redirection to multiple routes by changing the parameter.

The second method is an easy and elegant approach, if you just need redirection using the ng-href directive:

<div>
  <div ng-repeat="data in datas" title='{{ data.name }}'>
    <a ng-href="/{{ data.name }}">{{ data.name }}</a>
  </div><br/>
</div>
网友答案:

Use ng-click instead of onClick...

Controller

...
$scope.redirect = function(route) {
   $location.path('/' + route);
}
...

Template

<div>
    <div ng-repeat="data in datas" title='{{ data.name }}' ng-click="redirect({{ data.name }})" >{{ data.name }}</div><br/>
</div>

...or use an anchor tag and ng-href.

<div>
    <div ng-repeat="data in datas" title="{{ data.name }}"><a ng-href="\{{ data.name }}">{{ data.name }}</a></div><br/>
</div>
相关阅读:
Top