使用 Angular 动态更新 CSS 类
Dynamically Updating a CSS Class using Angular
我有一个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 函数将触发。但是,选择条带是条带的 ID。来自 XAML 背景,我习惯于拥有整个对象。虽然我知道我可以编写一个实用程序方法来循环遍历 stripe 对象并找到具有相应 ID 的对象,但对于此类任务来说,这似乎是相当手动的。
有没有比编写我提到的实用程序方法更优雅的方法?如果是这样,如何?
谢谢!
你根本不需要在$scope
中getStripeCss
函数。
如果您希望变量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' }
};
相关文章:
- Css order属性不't在Jquery设置时更新
- jQuery整个页面正在重新加载以更新css
- 在Scroll上更新CSS代码:简化它就不会了'不要使用JQuery和最简单的Javascript
- Jquery在CSS下面更新
- 通过两种方法创建和更新 CSS
- Jquery动态更改CSS主题-强制更新类
- 当我尝试在网页中使用更新面板时,CSS不起作用
- CSS转换未在增加高度时更新背景色
- jQuery.CSS没有更新背景
- CSS在第一次点击jQuery.post提交时没有应用,然后在随后的点击中没有更新
- Javascript href 属性用于 css 未更新
- 在小间隔内通过javascript更新css时,会出现断断续续的动态观察动画
- 使用jQuery更新CSS属性
- CSS/JS未在Magento中更新
- 具有新创建的行的 Javascript tr 单击事件(更新 css)
- 如何在 css 中更新参数
- JavaScript/CSS-更新多个输入元素的值*和*大小
- 在不同的 DOM 元素中组合/批处理多个 CSS 更新以减少重排/重绘
- 我如何使我的CSS更新一致
- 汤博乐:如何用后标记控制CSS(更新:没有JQuery的工作方法!)