AngularJS forEach 函数 - 无法解析为真

AngularJS forEach function - cannot get to resolve to true

我的控制器中有以下代码:

    $scope.checkSchedule = function (value) {
        var result = false;
        angular.forEach($scope.shifts, function (obj) {

            if (obj['PublishedEmployee.Id'] === value && result === false) {
                result = true;
            }

        });
        return result;
    };

我的$scope.shifts是一个对象数组。每个对象都包含另一个对象 PublishedEmployee,并且该对象的 属性 为 Id

我的目标是遍历 $scope.shifts 个对象,如果 PublishedEmployee.Id 属性 == $scope.currentId 然后将函数解析为 true .

在我的 HTML 中,我有以下内容:

ng-show="checkSchedule(currentId)"

因此,如果函数解析为真,则元素将显示。但是,我总是收到 false,我缺少什么来相应地解决这个问题?

图片:

您的问题是您正在检查文字 属性 "PublishedEmployee.Id" 而不是 "PublishedEmployee".[=18= 的子 属性 "Id" ]

改变

if (obj['PublishedEmployee.Id'] === value && result === false)

if (!result && obj.PublishedEmployee && obj.PublishedEmployee.Id === value)

这将在尝试比较 Id 属性.

之前检查 PublishedEmployee 属性 是否存在

如果您只想检查 $scope.shifts 是否匹配,您可以使用 Array.prototype.some.

return $scope.shifts.some(function(obj) {
    return obj.PublishedEmployee && obj.PublishedEmployee.Id === value;
});

理论上,如果您的数据如您所说,这将有效...

<div ng-repeat="item in shifts">
    <div ng-show="item.PublishedEmployee.Id == currentId">
        Matched
    </div>
</div>