简体   繁体   中英

(angularJS) make ng-click open a link on an ng-repeat

New to Angular, so sorry if this has been covered somewhere but it's hard for me to explain exactly what I want in succinct terms.

Currently I have an ng-repeat pulling data from a JSON object and making a list.

<li ng-click="openLink()" ng-repeat="location in locations">
  {{location.name}}
</li>

Each object has a key called "link" and that key has a property that is a url. I want the function openLink() to open the link associated with each object. I'm not sure how to go about this in the controller.

I know i can do

<li ng-click="openLink()" ng-repeat="location in locations">
  <a ng-href="{{location.link}}">{{location.name}}</a>
</li>

but i'd like to be able to do it with ng-click instead to keep the index.html cleaner. So what do I put in here to accomplish the same thing?

$scope.openLink = function() {

};

If the url that you want to redirect to is a route in your angular app, you need to inject the $location service into the controller, then in your function, set the path property on $location.

<li ng-click="openLink(location)" ng-repeat="location in locations">
  {{location.name}}
</li>


$scope.openLink = function(location){
    $location.path(location.link);
}

If the location link is a complete url, you should inject the $window service into your controller, and change the openLink function to set $window.location.href.

$scope.openLink = function(location){
    $window.location.href = location.link;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM