Reputation: 9806
I've created a filter that checks the user id and then filters out all results in a ng-repeat that don't have that user id.
If I place my filter,
UserService.getCurrentUser()
.then(function(user_id){
$scope.user_id = user_id;
});
In my controller it works fine, but I want to keep my controller as clean as possible so I want to move it out.
I created a file called "userFilter.js" and this is the code,
angular.module('addMovieseat', [])
.filter('user_filter', function() {
UserService.getCurrentUser()
.then(function(user_id){
$scope.user_id = user_id;
});
});
But when I inject the filter into my controller I get an error,
Error: [$injector:unpr] Unknown provider: user_filterProvider <- user_filter <- addMovieCtrl
Also this is my service where I get my current user id,
(function(){
"use strict";
angular.module('addMovieseat')
.factory('UserService', function($http, $q){
return{
getCurrentUser: function(){
var user_id = null,
deferred = $q.defer();
// Get the current user id and use it to filter out all movies that do not correspond to that id in the main overview.
$http.get(('/users.json'),{ cache: true}).
success(function (data, status, headers, config) {
if (status == 200) {
deferred.resolve(data.id);
} else {
deferred.resolve(false);
console.error('Error happened while getting the user list.')
}
});
return deferred.promise;
}
}
});
})();
Upvotes: 1
Views: 74
Reputation: 5435
i actually think what your are looking for is
<li ng-repeat="movie in movies|filter:{user_id:user:id}:strict"></li>
as shown here https://docs.angularjs.org/api/ng/filter/filter
using ng-if might lead to weird behavior under certain circunstances make sure you read https://docs.angularjs.org/api/ng/directive/ngIf
Upvotes: 1
Reputation: 272
It sounds as if you might be better served using ng-if
on your repeated items. Like this
<li ng-repeat="movie in movies" ng-if="movie.user_id == user_id"></li>
Assuming $scope.user_id
in your controller is the id being checked for, and your list of movies is an array. Like this:
$scope.user_id = 'Tim';
$scope.movies = [
{name: 'Movie Title 1', user_id: 'Tim'},
{name: 'Movie Title 2', user_id: 'Jane'},
{name: 'Movie Title 3', user_id: 'Bob'}
];
This will only render the movie with user_id 'Tim'.
EDIT: Documentation for ng-if
EDIT 2: Based on the comment by OP, updated code to reflect specific issue.
Upvotes: 2