I have an AngularJS app. I'm trying to learn the right way to do things in Angular and gain a better understanding of the framework. With that in mind, I have an app that looks like the following:
index.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>
mycontrollers.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;
}
}
I'm trying to figure out how to dynamically change the DIV element style when a user chooses an option in the drop down. At this time, the getStripeCss function fires. However, selectedStripe is the id of the stripe. Coming from a XAML background, I'm used to having the entire object. While I understand that I could write a utility method that loops through the stripe objects and finds the one with the corresponding ID, this seems fairly manual for this kind of task.
Is there a more elegant approach than writing the utility method as I mentioned? If so, how?
Thank you!