如何使第一个链接打开一个特定的链接

How to make the first link open a specific link

本文关键字:链接 一个 第一个 何使      更新时间:2023-09-26

我有将打开html中定义的链接的表,但我想使第一个链接打开一个不同的链接,如:john.com,这是可能的吗?

所以名字:John将打开john.com

html:

<div ng-controller="MyCtrl">
  <div class="container">
    <table class="table">
      <thead>
        <tr>
          <th>Firstname</th>
          <th>Lastname</th>
          <th>Email</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="person in data">
          <th><a href="">{{person.name}}</a></th>
          <th>{{person.lastName}}</th>
          <th ng-click="colorRow($index)" ng-class="{yellow : $index == row}" ng-show="$index != row ">{{person.email}}</th>
          <th ng-show="$index == row" class="yellow"> Cliked</th>
        </tr>
      </tbody>
    </table>
  </div>
</div>

js:

var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
  $scope.row = -1;
  $scope.data = [{
    "email": 'john@example.com',
    name: "John",
    lastName: "Doe"
  }, {
    "email": 'mary@example.com',
    name: "elton",
    lastName: "Junior"
  }, {
    "email": 'july@example.com',
    name: "mark",
    lastName: "Junior"
  }, ]
  $scope.colorRow = function(index) {
    $scope.row = index;
    console.log("Hey Joe", index)
  }
}
css:

.odd {
  background-color: white;
}
.even {
  background-color: grey;
}
.yellow {
  background-color: yellow;
  color: green;
}
http://jsfiddle.net/71rqq1o1/22/

您可以通过检查html文件中的$index语句来实现这一点,例如:

<th><a href="{{$index === 0 ? 'http://google.com' : 'http://'+person.name}}">{{person.name}}</a></th>

但是我建议你不要使用html文件中的逻辑,而在html中使用视图模型之类的东西。你必须在控制器中单独确认你的数据。

像这样:

function toViewModel(data) {
  return data.map((d, i) => {
    let obj = {};
    if (i === 0) {
      obj.link = "http://google.com";
    } else {
      obj.link = `http://${d.name}.com`;
    }
    obj.name = d.name;         // you can use some libs to extend objects (e.g. lodash) instead of reassigning each attr
    obj.lastName = d.lastName;
    obj.email = d.email;
    return obj;
  });
}
$scope.viewdata = toViewModel(mydata);

在html中使用你的视图模型,只是使用对象的纯属性,没有任何逻辑。

<th><a href="{{person.link}}">{{person.name}}</a></th>