我正在使用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>
答案 0 :(得分:2)
您的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;
};