AngularJS工厂

地缘

我对angularjs有点陌生,我正在尝试创建一个小型电影数据库。这是我第一次使用工厂,我想确保这是正确的方法,以及如何在下面显示的其他功能中使用该工厂?

我希望该工厂仅运行一次,因此我可以在任何我喜欢的控制器中使用它。但是我不知道为什么在下面的示例中不能使用$ scope.allMovies。提前致谢!

var app = angular.module('myApp', []);

app.factory('moviesService', ['$http', function($http) {

  var allMovies = [];

  var getMovies = function() {
      $http.get('js/data.json').success(function(data) {
          angular.forEach(data, function(movies) {
          allMovies.push(movies);         
      });
  })
}

getMovies();

var getAllMovies = function(){
      return allMovies;
}

return {
    getAllMovies: getAllMovies
};

}]);

app.controller('listController', ['$scope', 'moviesService', function($scope,moviesService) {

$scope.genres = ['All', 'Crime', 'Drama', 'Action', 'Comedy'];

$scope.allMovies = moviesService.getAllMovies();

$scope.moviesByGenre = [];

$scope.selectedGenre = 'All';

$scope.getMoviesByGenre = function() {
    // code to get movies by genre goes here
    // cant access $scope.allMovies from here, returns as an empty array
};
}]);

我的index.html看起来像:

<div ng-controller="listController">
    <div ng-repeat="movies in allMovies">{{movies.title}}</div>
</div>

这有效,我有从data.json获得的movies.title列表。

但是,当我尝试从功能getMoviesByGenre内部来console.log $ scope.allMovies时,我得到了一个Emtpy数组。

玛丽安·班

这是因为服务内部的http请求是异步执行的。为了克服这个问题,您可以使用$ watchCollection函数,该函数将在moviesService中修改所有movie数组后执行:

app.controller('listController', ['$scope', 'moviesService', function($scope, moviesService) {
   $scope.genres = ['All', 'Crime', 'Drama', 'Action', 'Comedy'];

   $scope.allMovies = moviesService.getAllMovies();

   $scope.moviesByGenre = [];

   $scope.selectedGenre = 'All';

   $scope.getMoviesByGenre = function() {
       // code to get movies by genre goes here
       // cant access $scope.allMovies from here, returns as an empty array
   };
  $scope.$watchCollection('movies', function (newValue) {
      getMoviesByGenre();
  });
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章