【问题标题】:ng-class - finding a value inside objectng-class - 在对象内部查找值
【发布时间】:2015-09-15 10:39:29
【问题描述】:

我有一个看起来像这样的对象:

$scope.things = [
    {
        name: 'Bob!',
        short_name: 'bob',
        info: 'something something'
    },
    {
        name: 'Steve',
        short_name: 'steve',
        info: 'something something something'
    },
];

我像这样遍历它们并添加一个 ng-click:

<div ng-repeat="thing in things" ng-click="addThing(thing.name, thing.short_name, thing_info" ng-class="thingClass(thing.name)">content goes here</div>

ng-click="addThing()" 基本上将值组合起来并将它们添加到对象中。

单击时,它应该添加类selected - 当我不使用多维对象时,这工作得很好而且花哨,因为它只是在对象/数组中寻找name(此时,我认为它是一个对象......但当时它是一个数组)

我不知道如何做与此相同的操作...

$scope.thingClass= function(name) {
    if($scope.thingSelected.indexOf(name) != -1) {
        return 'selected';
    }
};

...现在的对象。我试图从这里改编一些通过谷歌找到的答案,例如:

$scope.teamClass = function(name) {

    var found = $filter('filter')($scope.thingSelected, {id: name}, true);

    if (found.length) {
        return 'selected';
    }

};  

...但没有喜悦。

谁能指出/推动我正确的方向?

【问题讨论】:

  • $scope.thingSelected$scope.things 中的对象之一吗?
  • 这里打错了ng-click="addThing(thing.name, thing.short_name, thing.info)"
  • $scope.thingSelected 是什么?它是一个对象数组,保存每个添加的对象,还是一个数组??
  • 请给个笨蛋。函数调用中的拼写错误和添加类没有正确完成
  • wero,是的 - 那里不是 100% 清楚,但我使用 $scope.things 创建项目列表(使用 ng-repeat),如果单击一个项目,它都会添加到 $ scope.thingSelected 并且还应该通过添加一个类来标记该项目

标签: angularjs javascript-objects ng-class


【解决方案1】:

您可以简单地将事物对象传递给thingClass

... ng-class="thingClass(thing)" ...

并按如下方式实现thingClass

$scope.thingClass= function(thing) {
    return $scope.thingSelected.indexOf(thing) >= 0 ? 'selected' : '';
}

也许您也应该将此技术应用于addThing

... ng-click="addThing(thing)" ...

$scope.addThing = function(thing) {
    if ($scope.thingSelected.indexOf(thing) < 0)
        $scope.thingSelected.push(thing);
}

但是,与其在数组中跟踪选定的事物,不如在每个事物中引入selected 属性要容易得多:

$scope.addThing = function(thing) {
    thing.selected = true;
}

$scope.thingClass= function(thing) {
    return thing.selected ? 'selected' : '';
}

【讨论】:

  • 啊,我明白了,我的印象是我不能像那样传递整个对象,不知道我从哪里得到这种印象(可能是一些不相关的问题)......有些重新- 我认为需要写,谢谢
猜你喜欢
  • 2021-06-05
  • 2014-07-03
  • 1970-01-01
  • 1970-01-01
  • 2022-08-11
  • 1970-01-01
  • 1970-01-01
  • 2016-10-29
  • 1970-01-01
相关资源
最近更新 更多