我正在开发AngularJS应用程序。我想知道如何查询变量的兄弟属性。例如在我的控制器变量车存在。
rootApp.controller('Option2', function($scope){
$scope.cars = [
{model : "Ford Mustang", color : "red"},
{model : "Fiat 500", color : "blue"},
{model : "Volvo XC90", color : "black"}
];
});
我要求用户从选择选项中选择模型,我想打印所选汽车的颜色。
<p>Select a Car</p>
<select ng-model="selectedCar">
<option ng-repeat="x in cars" value="{{x.model}}">{{x.model}}</option>
</select>
<p>Color of this car is <b style="color:{{selectedCar.color}}">{{selectedCar.color}}</b></p>
此处,selectedCar
的值取x.model
而非x
。如何获取model
的兄弟属性,即同一变量的color
?
答案 0 :(得分:0)
angular.element(document).ready(function() {
var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope', 'store', function($scope, store) {
$scope.search = '';
$scope.cars = [];
$scope.cars = store.getCars();
$scope.filterProductsByCategory = function(category) {
$scope.search = category;
};
}]);
app.factory('store', function() {
var cars = [
{model : "Ford Mustang", color : "red"},
{model : "Fiat 500", color : "blue"},
{model : "Volvo XC90", color : "black"}
];
return {
getCars: function() {
return cars;
}
};
});
angular.bootstrap(document, ['myApp']);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<h2>Search Car: </h2>
<input type="text" ng-model="search" placeholder="Search..." />
<table cellpadding="5" cellspacing="1" border="1" style="width:100%;">
<tr>
<th>Model</th>
<th>Color</th>
</tr>
<tr ng-repeat="car in cars | filter:search | orderBy:'name'">
<td>{{car.model}}</td>
<td>{{car.color}}</td>
</tr>
</table>
</div>
<div>
</div>
&#13;
答案 1 :(得分:0)
您可以稍微更改模板代码,这样做很好。
我已将Array Key添加为所选选项中的值,并根据该键显示汽车的值或您阵列中的特定索引
<p>Select a Car</p>
<select ng-model="selectedCar">
<option ng-repeat="(key,x) in cars" value="{{key}}">{{x.model}}</option>
</select>
<p>Color of this car is <b style="color:{{cars[selectedCar].color}}">{{cars[selectedCar].color}}</b></p>
答案 2 :(得分:0)
使用ngOptions代替 ng-repeat
来迭代选项。
<强>样本强>
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.cars = [
{model : "Ford Mustang", color : "red"},
{model : "Fiat 500", color : "blue"},
{model : "Volvo XC90", color : "black"}
];
$scope.selectedModel = function(model) {
console.log("model");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<p>Select a Car</p>
<select ng-model="selectedCar" ng-options="x.model for x in cars"></select>
<p>Color of this car is <b style="color:{{selectedCar.color}}">{{selectedCar.color}}</b></p>
</div>