AngularJs - forEach作用域数组-不工作

AngularJs - forEach scope array - not working

本文关键字:工作 数组 作用域 forEach AngularJs      更新时间:2023-09-26

我知道我做了一些愚蠢的事情,所以请原谅我:

Html:

Filter: <input type="radio" ng-model="Type" value="Rear"> Rear
<input type="radio" ng-model="Type" value="Front"> Front
<br>
Select:
<name-value-select  entry="entry" field="axleType" options="filterTypes"></name-value-select>

控制器:

$scope.$watch('Type', function (Type) {
    $scope.filterTypes = [];
    if ($scope.axleTypes == undefined || $scope.axleTypes == []) {
        $scope.axleTypes = API.GetAxleTypes;
    }
    angular.forEach($scope.axleTypes, function (type) {
        console.log('axleType: ' + type);
        console.log('Type: ' + type);
        if (axleType.Type == Type) {
            this.push(axleType);
        }
    }, $scope.filterTypes);
    $scope.filterTypes.sort(function (a, b) {
        return a.Description.localeCompare(b.Description);
    });
});

我甚至不能在watch函数中循环遍历axleTypes数组。它似乎没有拾取一个奇怪的集合,因为它绕过填充未定义或[]的axleTypes。

我在做蠢事,我自己都看不出来。

Update: Per Jason's request

(1) My angular controller:

$scope.entry = {
    Description: ''
};
$scope.Type = 'Front';
$scope.entry.type = '';
$scope.$watch('Type', function (Type) {
    $scope.filterTypes = [];
    $scope.axleTypes = new API.GetAxleTypes(function (axleTypes) {
        angular.forEach($scope.axleTypes, function (axleType) {
            if (axleType.Type == Type) {
                this.push(axleType);
                }
        }, $scope.filterTypes);
    });
    $scope.filterTypes.sort(function (a, b) {
        return a.Description.localeCompare(b.Description);
    });
});

(2)我的Html:

Filter: <input type="radio" ng-model="Type" value="Rear"> Rear
<input type="radio" ng-model="Type" value="Front"> Front
<br>
Select:
<name-value-select entry="entry" field="axleType" options="filterTypes"></name-value-select>

没有更多的错误杰森,然而,当我切换两个单选按钮什么都没有发生,即,前轴仍然显示当我选择后轴单选按钮。啊。

很好。我觉得这就是你想做的。基本上,你要先加载数据,然后设置手表。这样我们就不会多次调用异步调用。我修改了普朗克使用这种方法http://plnkr.co/edit/lQbn4hXmJ1Z4YpKdb4u3?p=preview:

$scope.axleTypes = API.GetAxleTypes(function () {
    $scope.$watch('Type', function (Type) {
        $scope.filterTypes = [];
        angular.forEach($scope.axleTypes, function (type) {
            console.log('axleType: ' + type);
            console.log('Type: ' + type);
            if (axleType.Type == Type) {
                this.push(axleType);
            }
            if(!$scope.$$phase) $scope.$digest();
        }, $scope.filterTypes);
    });
});
$scope.filterTypes.sort(function (a, b) {
    return a.Description.localeCompare(b.Description);
});