tabset中的AngularJS $范围问题

时间:2015-04-01 14:05:01

标签: javascript angularjs angularjs-scope angular-ui angular-ui-tabset

我尝试在控制器中查看视图中过滤器生成的集合时遇到问题。

我将过滤后的数据存储在变量中:

 <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子项。

我希望你们能知道这里发生了什么,

干杯

3 个答案:

答案 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)

您认为tabsettab创建新范围是正确的。因此,您正在丢失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

相关问题