过滤用户ID

时间:2015-11-14 16:47:30

标签: angularjs

我有连接表,用于在我的电影和用户表之间创建关联。如果我使用,

"ng-repeat" => "movie in movies"

我收到了所有用户添加的所有电影。所以我试图过滤掉与用户ID不对应的所有结果。

这是我movies_users请求的JSON结果,

{"id":4,
  "title":"Creed",
  "release_date":"2016-01-21",
  "image":"/xSE4NBFDzqedwa4AIj99r1Z7ljF.jpg",
  "user_id":null,
  "created_at":"2015-11-14T12:07:43.434Z",
  "updated_at":"2015-11-14T12:07:43.434Z",
  "movie_id":"312221",
  "users":[
    {"id":2,"email":"jan@jan.com","provider":null,"uid":null,"name":"Jan Jansen","username":null},
    {"id":1,"email":"peter@peter.nl","provider":null,"uid":null,"name":"Peter Boomsma","username":null}]
},

{"id":5,
  "title":"Star Wars: Episode VII - The Force Awakens",
  "release_date":"2015-12-17",
  "image":"/fYzpM9GmpBlIC893fNjoWCwE24H.jpg",
  "user_id":null,
  "created_at":"2015-11-14T12:13:40.413Z",
  "updated_at":"2015-11-14T12:13:40.413Z",
  "movie_id":"140607",
  "users":[
    {"id":1,"email":"peter@peter.nl","provider":null,"uid":null,"name":"Peter Boomsma","username":null}]
}

正如您所看到的那样,电影中有相关的用户,但我想知道如何才能在视图中显示也具有用户ID的电影。

我有这个,

.movie_container{
  "ng-if" => "movie.user_id == user_id", 
  "ng-repeat" => "movie in movies | orderBy:'release_date'"
 }

但是现在我已经改变了我的数据库/后端它不再起作用了。

修改

loadMovies函数

   movieService.loadMovies().then(function(response) {
      $scope.movies = response.data;

      $scope.checkUserExists = function(movie_users) {
        for(var i = 0; i < movie_users.length; i++) {
            if(movie_users[i].id === movie.user.id) {
                return true;
            }
        }
        return false;
      }

    })

1 个答案:

答案 0 :(得分:1)

创建一个将在ng-if指令内调用的函数,并将影片可迭代的用户数组传递给它:

ng-if="checkUserExists(movie.users)"

现在,在控制器中定义函数:

$scope.checkUserExists(movie_users) {
    for(var i = 0; i < movie_users.length; i++) {
        if(movie_users[i].id === user_id) {
            return true;
        }
    }
    return false;
}