Reputation: 9838
I am using an ng-repeat directive with filter like so:
<tr ng-repeat="entry in (filteredEntries = (entries | filter:hasGroup | filter:readingFilter | orderBy:data.sortType:data.sortReverse:true))"></tr>
<span>{{filteredEntries.length}}</span>
I'm using $stateProvider to load views and controllers
$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",
})
Here is a snippet from my controller:
.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);
});
There is no problem with such a code, however I need to access filteredEntries attribute in my controller using $scope.filteredEntries
which should be ok with no problem. Unfortunately this didn't work and I couldn't figure it out why this is happening.
Upvotes: 3
Views: 2110
Reputation: 1237
You can access the filtered array in BOTH VIEW AND CONTROLLER using this method:
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>
Updated for your example with updated code.
So, in your state provider for the data route, add "controllerAs: 'vm',":
.state('data', {
url: "/data",
templateUrl: viewsPrefix + "data.html",
data: {
pageTitle: 'Data'
},
controllerAs: 'vm',
controller: "DataCtrl",
})
Then, in your controller:
.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);
}
});
And finally, in your template (added button to test logging entries):
{{filteredEntries.length}}
<button ng-click="vm.logEntries()">LOG Entries</button>
<br><br>
Upvotes: 1