Javascript 如何有条件地在 ng 样式中应用动态值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41870532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:43:13  来源:igfitidea点击:

How to apply a dynamic value in ng-style conditionally?

javascriptcssangularjs

提问by Mistalis

I would like to apply a background-colorwith ng-styleconditionally when the color value can be updated from $scope.

我想申请一个background-colorng-style有条件时,颜色值可以被更新$scope

Here are my variables in scope:

这是我在范围内的变量:

$scope.someone = { id: '1', name: 'John', color: '#42a1cd' };
$scope.mainId = 1;

Actually I don't use any condition to apply the background color, it is done with:

实际上我不使用任何条件来应用背景颜色,它是通过以下方式完成的:

<div ng-style="{'background-color': someone.color}">
    {{someone.name}}
</div>


The idea here is to apply this background color only when someone.id == mainId. I tried several solutions, but it does not seems to be the correct synthax:

这里的想法是仅在someone.id == mainId. 我尝试了几种解决方案,但它似乎不是正确的合成器:

  • ng-style="{{someone.id == mainId}} ? ('background-color': {{someone.color}}) : null"
  • ng-style="{ ('background-color': someone.color) : someone.id == mainId }"
  • ng-style="{{someone.id == mainId}} ? ('background-color': {{someone.color}}) : null"
  • ng-style="{ ('background-color': someone.color) : someone.id == mainId }"


JSFiddle for testing

用于测试的 JSFiddle

Does someone have an idea of how I can achieve this?

有人知道我如何实现这一目标吗?

采纳答案by Fissio

This seems to work fine.

这似乎工作正常。

ng-style="{'background-color': person.id === mainId ? person.color : ''}"

See updated fiddle with two people - the one with mainIdhas a background color, while the other doesn't: http://jsfiddle.net/fgc21e86/7/

看到两个人的更新小提琴 - 一个mainId有背景颜色,而另一个没有:http: //jsfiddle.net/fgc21e86/7/

回答by Ashish Bakwad

You may try like this

你可以这样试试

<div ng-app="myApp" ng-controller="MyCtrl">
  <div ng-style="{'background-color': getColor(someone)}">
    {{someone.name}}
  </div>
</div>

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
  $scope.someone = {
    id: 1,
    name: 'John',
    color: '#42a1cd'
  };
  $scope.getColor = function(someone) {

        if($scope.mainId === someone.id) {
        return someone.color;
      }
  }
  $scope.mainId = 1;
}]);

回答by strwoc

You could do it like

你可以这样做

ng-style="someone.id == mainId ? {'background-color':'{{someone.color}}'} : {'background-color':'red'}"

Here's an updated fiddle http://jsfiddle.net/fgc21e86/9/

这是更新的小提琴http://jsfiddle.net/fgc21e86/9/