我有一个AngularJS应用程序。我试图学习正确的方式来处理Angular中的事情并更好地理解框架。考虑到这一点,我有一个看起来如下的应用程序:
<!DOCTYPE html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="myControllers.js"></script>
<style type="text/css">
.init { border: solid 1px black; background-color: white; color: black; }
.red { background-color:red; color:white; border:none; }
.white { background-color: white; color: black; border:none; }
.blue { background-color:blue; color:white; border:none; }
</style>
</head>
<body ng-controller="StripeListCtrl">
<select ng-options="stripe.id as stripe.name for stripe in stripes" ng-model="selectedStripe">
<option value="">Select a Stripe Color</option>
</select>
<div ng-class="{{getStripeCss()}}">
You chose {{selectedStripe.name}}
</div>
</body>
</html>
function StripeListCtrl($scope) {
$scope.selectedStripe = null;
$scope.stripes = [
{ name: "Red", id=2, css: 'red' },
{ name: "White", id: 1, css: 'white' },
{ name: "Blue", id: 5, css: 'blue' }
];
$scope.getStripeCss = function() {
if ($scope.selectedStripe == null) {
return "init";
}
return $scope.selectedStripe.css;
}
}
当用户在下拉列表中选择一个选项时,我试图弄清楚如何动态更改DIV元素样式。此时,getStripeCss函数将触发。但是,selectedStripe是条带的id。来自XAML背景,我曾经拥有整个对象。虽然我知道我可以编写一个实用程序方法来遍历条带对象并找到具有相应ID的那个,但对于这种任务来说这似乎是相当手动的。
有没有比我提到的实用方法更优雅的方法?如果是这样,怎么样?
谢谢!
答案 0 :(得分:4)
您根本不需要getStripeCss
中的$scope
功能。
如果您希望变量selectedStripe
存储对象,则需要像这样更改ng-options
:
<select ng-options="stripe.name for stripe in stripes" ng-model="selectedStripe">
<option value="">Select a Stripe Color</option>
</select>
<div ng-class="{red:selectedStripe.id==2, white:selectedStripe.id==1,
blue:selectedStripe.id==5}">
You chose {{selectedStripe.name}}
</div>
但是,如果您希望selectedStripe
存储密钥(就像您当前正在执行的操作)并希望访问stripes
数组/对象中的项目而不循环覆盖它们,您可以执行类似这样的操作:
<select ng-options="key as value.name for (key,value) in stripes"
ng-model="selectedStripe">
<option value="">Select a Stripe Color</option>
</select>
<div ng-class="{red:selectedStripe==2, white:selectedStripe==1,
blue:selectedStripe==5}">
You chose {{stripes[selectedStripe].name}}
</div>
更改模型:
$scope.stripes = {
2:{ name: "Red", id:2, css: 'red' },
1:{ name: "White", id: 1, css: 'white' },
5:{ name: "Blue", id: 5, css: 'blue' }
};