我尝试在控制器中查看视图中过滤器生成的集合时遇到问题。
我将过滤后的数据存储在变量中:
<table class="table">
<tr ng-repeat="item in filteredCollection = (myCollection | filter: txtSearch)">
<td ng-bind="item"></td>
</tr>
</table>
我想在我的控制器中订阅'filteredCollection'的更改:
$scope.$watchCollection('filteredCollection', function() {
if (typeof($scope.filteredCollection) != 'undefined')
console.log('Results changed : ' + $scope.filteredCollection.length);
});
我已设置this JSFiddle向您显示我的问题:我的监视功能永远不会被调用。
有趣的是,当我删除HTML中的所有<tabset> <tab>
标记时,它会起作用。我想我搞砸了$ scope,但我不明白为什么。也许tabset会创建一个新的$ scope子项。
我希望你们能知道这里发生了什么,
干杯
答案 0 :(得分:1)
尝试将filteredCollection
放入对象中,因此它将更改正确的范围属性:
$scope.obj = { filteredCollection : [] };
$scope.$watchCollection('obj.filteredCollection', function(newVal) {
if (typeof($scope.obj.filteredCollection) != 'undefined')
console.log('Results changed : ' + $scope.obj.filteredCollection.length);
});
在HTML中:
<tr ng-repeat="item in obj.filteredCollection = (myCollection | filter: txtSearch)">
请参阅此fiddle。
答案 1 :(得分:1)
您认为tabset
和tab
创建新范围是正确的。因此,您正在丢失filteredCollection
的上下文,因为现在正在tab
指令范围的上下文中创建它。
Angular最近添加了controllerAs
语法,有助于避免这种情况。它允许我们更好地确定正在执行的范围。
我已使用controllerAs
语法更新了您的jsFiddle以显示这有何帮助。手表现在按预期点火了。
http://jsfiddle.net/hezwyjx1/2/
这是一个资源,可以帮助控制器作为语法:
http://toddmotto.com/digging-into-angulars-controller-as-syntax/
答案 2 :(得分:0)
这是另一篇解决此问题的帖子: https://github.com/angular-ui/bootstrap/issues/1553