2014-09-23 57 views
1

我有此数组项角:计数项相匹配的条件

[ 
    { 
    name: 'Foo', 
    completed: false 
    }, 
    { 
    name: 'Ninja', 
    completed: true 
    }, 
    { 
    name: 'Hello', 
    completed: true 
    }, 
    { 
    name: 'Baby', 
    completed: false 
    }, 
] 

的我想要显示的计数,其中完成了在我的视图=真。当元素从完成= false变为真时,我还需要此计数器自动更新。 有没有办法做到这一点在角?

回答

0

您可以采取多种方法,但都是先缓存控制器加载时完成的项目数。

您可以使用$watch函数来监视数组,并在对象更改时更新计数器。以下是未经测试,但应该给你怎么办呢

function myCtl($scope, itemFetcher) { 
    $scope.items = itemFetcher.get(); //retrieves your array of items 
    $scope.numComplete = countComplete(); 

    $scope.$watch("items", function(newValue, oldValue) { 
    $scope.items = newValue; 
    $scope.numComplete = countComplete(); 
    }, true); // NOTE: passing true into $watch is necessary to do a deep compare (i.e. comparing object properties), and I think it is required in this case, but it has a negative impact on performance & memory. 

    function countComplete() { 
    var cnt = 0; 
    angular.forEach($scope.items, function(item) { 
     cnt += item.completed ? 1 : 0; 
    } 
    return cnt; 
    } 
} 

或者,您可以更新在修改完成状态的项目功能完成计数感。以下代码也未经测试。

function myCtl($scope, itemFetcher) { 
    $scope.items = itemFetcher.get(); //retrieves your array of items 
    $scope.numComplete = countComplete(); 

    $scope.markItem = function(index, newState) { // this function is referenced in your HTML template 
    $scope.items[index].complete = newState; 
    $scope.numComplete += (newState) ? 1 : -1; 
    } 

    function countComplete() { 
    var cnt = 0; 
    angular.forEach($scope.items, function(item) { 
     cnt += item.completed ? 1 : 0; 
    } 
    return cnt; 
    } 
} 

使用$watch更方便和更不易出错,但可能会导致依赖于items阵列的大小的性能问题。第二种方法更高效,但更难维护。

5

您应该查看过滤器并使用它来动态地过滤您的数组; 在您的控制器声明你的过滤器这样

$scope.completedFilter(object) { 
    return object.completed === true; 
} 

后在你的模板,你可以再补充

{{(myArray | filter:completedFilter).length}} 

而且你数将与完成

注意自动改变:你也可以在你的模块中声明一个过滤器,如果你想在另一个控制器中重用它,可能是正确的

+0

想法不错,但我敢打赌,过滤方法与使用$ watch的大型数组项目具有相同的性能影响。这一切都取决于如何实现过滤器,我的猜测是它依赖于angular.equals这是一个潜在的性能杀手。 – Jason 2014-09-23 13:18:49

0

添加$ watch必需y?

尝试这种方式

$scope.itemCount = function() { 
    var cnt = 0; 
    angular.forEach($scope.items, function (item) { 
     cnt += item.completed ? 1 : 0; 
     console.log(item); 
    }); 
    return cnt; 
} 

只是为了检查计数得到更新我添加了一个项目上的按钮,点击物品数组

$scope.insertItem = function() { 
    $scope.items.push({ name: 'Phani', completed: true }); 

} 
{{itemCount()}} 

    <input type="button" ng-click="insertItem()" value="Insert" /> 

试试上面的方法