【问题标题】:Set and Display current Data on ng-click?在 ng-click 上设置和显示当前数据?
【发布时间】:2013-12-31 23:24:46
【问题描述】:

我正在使用 Yeoman - 角度生成器。
JSBin:JSBin Link

我有一个从工厂 angApp.factory("Airports", function() {}); 设置并从 ng-repeat <ul ng-repeat="airport in airports.detail"> 显示的机场的简单列表。

我希望有一个交互,当点击每个链接时,它将匹配机场代码并将其显示在新的段落标签<p class="current">Current: {{currentAirport.name}}</p>中。

为什么在html中点击机场链接时setAirport(airport.code)函数不会设置currentAirport.name(或显示?)?

控制器

angular.module("ang6App")
  .controller("AirportsCtrl", function ($scope, Airports) {
    $scope.formURL = "views/_form.html";
    $scope.currentAirport = null;
    $scope.airports = Airports;
    $scope.setAirport = function(code) {
      $scope.currentAirport = $scope.airports[code];
    };

  });

同一模块中的工厂服务

angApp.factory("Airports", function() {
    var Airports = {};
    Airports.detail = {
        "PDX": {
          "code": "PDX",
          "name": "Portland International Airport",
          "city": "Portland",
          "destinations": [
            "LAX",
            "SFO"
          ]
        },
        "STL": {
          "code": "STL",
          "name": "Lambert-St. Louis International Airport",
          "city": "St. Louis",
          "destinations": [
            "LAX",
            "MKE"
          ]
        },
        "MCI": {
          "code": "MCI",
          "name": "Kansas City International Airport",
          "city": "Kansas City",
          "destinations": [
            "LAX",
            "DFW"
          ]
        }
      };
    return Airports;
});

HTML

<div class="container" ng-controller="AirportsCtrl">
  <ul ng-repeat="airport in airports.detail">
    <li><a href="" ng-click="setAirport(airport.code)">{{airport.code}}</a> -- {{airport.city}} </li>
  </ul>
  <p class="current"> current: {{currentAirport.name}}</p>
</div>

【问题讨论】:

  • 你能设置一个显示这个[不]工作的小提琴吗?
  • 是的,我会尝试的。我非常不擅长构建 Angular 应用程序(使用 yeoman 来获得我的限制的一种作弊)
  • 一切就绪@drew_w 感谢您的帮助
  • 没问题,很高兴我能帮上忙!
  • 您何时可以发布答案,我正在积极等待将其标记为正确。或者,如果您还有其他问题,我正在等待

标签: javascript html angularjs yeoman angularjs-ng-click


【解决方案1】:

你的setAirport函数应该写成:

$scope.setAirport = function (code) {
  $scope.currentAirport = $scope.airports.detail[code];
};

但是,这可以通过直接传递实际的airport 对象来简化:

<a href ng-click="setAirport(airport)">{{airport.code}}</a>

$scope.setAirport = function (airport) {
  $scope.currentAirport = airport;
};

【讨论】:

  • 首选方法是什么?我觉得简化的答案更容易保留。但是,有没有不合适的时候?
  • 每种方法都为您提供完全相同的airport 对象,因此简单易行。唯一可能不起作用的情况是,例如,当您从数组中删除一个条目时,在这种情况下,您希望传入索引值(用于拼接),而不是实际的对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-30
  • 1970-01-01
  • 1970-01-01
  • 2020-06-08
  • 2016-10-06
  • 2016-11-08
  • 1970-01-01
相关资源
最近更新 更多