将计算的类添加到角度的HTML元素中

时间:2021-04-03 19:40:54

I render a bunch of user icons on a page. I want to give them a class based on their ID.

我在页面上渲染一堆用户图标。我想根据他们的ID给他们一个班级。

Example user object

示例用户对象

{ id: 1234, name: "foo" }

HTML element

<div ng-repeat="user in userList" class="something-{{ user.id % 10 + 1 }}">
</div>

So classes would be like "something-1", "something-2", ... based on the users ID.

因此,类似于“something-1”,“something-2”,...基于用户ID。

The above code doesn't work. No class shows up on the element. What is the right way to do this?

上面的代码不起作用。没有类出现在元素上。这样做的正确方法是什么?

3 个解决方案

#1


1  

Please give a try with ng-init. In that case your HTML will be

请试试ng-init。在那种情况下,您的HTML将是

<div ng-repeat="user in userList" ng-init="myId = (user.id % 10) + 1;" class="something-{{ myId }}">
</div>

#2


0  

Use ng-class

 <div ng-repeat="user in userList" data-ng-class="{class1:user.id===1234}"></div>

or you could use a function

或者你可以使用一个功能

<div ng-repeat="user in userList" class="{{getClassName(user)}}">
</div>

the function could be

功能可以

$scope.getClassName = function(user){
    return "class-" + (user.id * 10)+1; 
}

#3


0  

I would build the classes in the controller, so as to keep the view neat, tidy, and clean from JS operations that would be better suited in the controller.

我将在控制器中构建类,以便使JS操作保持整洁,整洁和清洁,从而更好地适应控制器。

users.forEach(function (user) {
  user.klass = 'something-' + (user.id % 10 + 1);
});

<div ng-repeat="user in users" class="{{::user.klass}}"> 
<!-- :: added. kill the watchers -->

#1


1  

Please give a try with ng-init. In that case your HTML will be

请试试ng-init。在那种情况下,您的HTML将是

<div ng-repeat="user in userList" ng-init="myId = (user.id % 10) + 1;" class="something-{{ myId }}">
</div>

#2


0  

Use ng-class

 <div ng-repeat="user in userList" data-ng-class="{class1:user.id===1234}"></div>

or you could use a function

或者你可以使用一个功能

<div ng-repeat="user in userList" class="{{getClassName(user)}}">
</div>

the function could be

功能可以

$scope.getClassName = function(user){
    return "class-" + (user.id * 10)+1; 
}

#3


0  

I would build the classes in the controller, so as to keep the view neat, tidy, and clean from JS operations that would be better suited in the controller.

我将在控制器中构建类,以便使JS操作保持整洁,整洁和清洁,从而更好地适应控制器。

users.forEach(function (user) {
  user.klass = 'something-' + (user.id % 10 + 1);
});

<div ng-repeat="user in users" class="{{::user.klass}}"> 
<!-- :: added. kill the watchers -->