我有一个 AngularJS 应用程序。我正在尝试学习在 Angular 中做事的正确方法,并更好地理解框架。考虑到这一点,我有一个如下所示的应用程序:
索引.html
<!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>
我的控制器.js
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 的对象,但这对于此类任务来说似乎相当手动。
有没有比我提到的编写实用程序方法更优雅的方法?如果是这样,怎么做?
谢谢!