我正在使用带有过滤器的 ng-repeat 指令:
<tr ng-repeat="entry in (filteredEntries = (entries | filter:hasGroup | filter:readingFilter | orderBy:data.sortType:data.sortReverse:true))"></tr>
<span>{{filteredEntries.length}}</span>
我正在使用$ stateProvider来加载视图和控制器
$stateProvider
.state('welcome', {
url: "/",
templateUrl: viewsPrefix + "welcome.html",
data: {
pageTitle: 'Welcome'
},
controller: "WelcomeCtrl"
})
.state('data', {
url: "/data",
templateUrl: viewsPrefix + "data.html",
data: {
pageTitle: 'Data'
},
controller: "DataCtrl",
})
以下是我的控制器的片段:
.controller('DataCtrl', ['$scope', '$rootScope', '$state', '$translate', '$filter') {
$scope.filteredEntries = [];
$scope.entries = [1, 2, 3, 4, 5, 6,7];
$scope.hasGroup = function(){return true;}
$scope.readingFilter = function(){return true;}
setInterval(function () {
console.log($scope.filteredEntries);
}, 500);
});
这样的代码没有问题,但我需要使用$scope.filteredEntries
访问我的控制器中的filteredEntries属性,这应该没问题。不幸的是,这不起作用,我无法弄清楚为什么会发生这种情况。
答案 0 :(得分:1)
您可以使用以下方法访问BOTH VIEW AND CONTROLLER中的已过滤数组:
var app = angular.module('test', []);
app.controller('MainCtrl', function() {
var vm = this;
vm.people = ['fox', 'rosi', 'err3', 'rob', 'cesar', 'geoff'];
vm.logPeople = function() {
console.log("FILTERED PEOPLE: ", vm.filteredPeople);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<div ng-app="test">
<div ng-controller="MainCtrl as vm">
<h2>List of people</h2>
Search: <input type="text" ng-model="search">
<ul>
<li ng-repeat="person in vm.filteredPeople = (vm.people | filter:search)">
{{person}}
</li>
</ul>
<p ng-hide="vm.filteredPeople.length">There is no result</p>
<button ng-click="vm.logPeople()">LOG PEOPLE</button>
<br><br>
Number of filtered people: {{vm.filteredPeople.length}}
</div>
</div>
针对更新代码的示例进行了更新。
因此,在数据路由的状态提供程序中,添加“controllerAs:'vm',”:
.state('data', {
url: "/data",
templateUrl: viewsPrefix + "data.html",
data: {
pageTitle: 'Data'
},
controllerAs: 'vm',
controller: "DataCtrl",
})
然后,在你的控制器中:
.controller('DataCtrl', ['$scope', '$rootScope', '$state', '$translate', '$filter') {
var vm = this;
vm.filteredEntries = [];
vm.entries = [1, 2, 3, 4, 5, 6,7];
vm.hasGroup = function(){return true;}
vm.readingFilter = function(){return true;}
vm.logEntries = function() {
console.log("FILTERED Entries: ", vm.filteredEntries);
}
});
最后,在您的模板中(添加按钮来测试日志记录条目):
{{filteredEntries.length}}
<button ng-click="vm.logEntries()">LOG Entries</button>
<br><br>