繁体   English   中英

使用Angular动态更新CSS类

[英]Dynamically Updating a CSS Class using Angular

我有一个AngularJS应用。 我正在尝试学习在Angular中做事的正确方法,并更好地了解框架。 考虑到这一点,我有一个类似于以下内容的应用程序:

的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;
    }
}

我试图找出当用户在下拉菜单中选择一个选项时如何动态更改DIV元素样式的方法。 此时,将触发getStripeCss函数。 但是,selectedStripe是条纹的ID。 来自XAML背景,我习惯使用整个对象。 虽然我知道我可以编写一个实用程序方法来遍历条带化对象并找到具有相应ID的实用程序,但对于这种任务来说,这似乎相当手动。

是否有比我提到的编写实用程序方法更好的方法? 如果是这样,怎么办?

谢谢!

getStripeCss不需要$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' }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM