[英]AngularJS $scope issues in 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);
});
我已經設置了這個JSFiddle來向您展示我的問題:從未調用過我的watch函數。
有趣的事實,當我刪除HTML中的所有<tabset> <tab>
標記時,它可以工作。 我想我搞砸了$ scope,但是我不明白為什么。 選項卡可能會創建一個新的$ scope子級或其他名稱。
我希望你們會發現這里發生了什么,
干杯
嘗試將filteredCollection
放在一個對象中,這樣它將更改正確的scope屬性:
$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)">
看到這個小提琴 。
您認為tab
tabset
和tab
創建新作用域是正確的。 因此,您丟失了filteredCollection
的上下文,因為現在正在tab
指令范圍的上下文中創建它。
Angular最近剛剛添加了controllerAs
語法,可幫助避免出現這種情況。 它使我們能夠更好地確定在什么范圍內執行某項操作。
我已經使用controllerAs
語法更新了您的jsFiddle,以顯示其幫助。 手表現在可以正常啟動。
http://jsfiddle.net/hezwyjx1/2/
這是一些有關控制器語法幫助的資源:
http://toddmotto.com/digging-into-angulars-controller-as-syntax/
這是另一篇有關此解決方案的文章: https : //github.com/angular-ui/bootstrap/issues/1553
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.