将排序添加到Angular工厂

莱瑟德

我想在Angular JS中向我的工厂控制器添加排序功能。我已经了解到以下内容:

var albumsApp = angular.module ('albumsApp',[])


        albumsApp.factory('albumFactory',function($http) {
        return {
            getAlbumsAsync: function(callback,$scope){

                $http.get('albums.json').success(callback);
                },

            };


        });
        albumsApp.controller ('albumController', function ($scope,albumFactory) {
            albumFactory.getAlbumsAsync(function(results){
            console.log('albumController async returned value');
            $scope.albums = results.albums;
                });
            albumFactory.changeSorting(function(results){
            console.log('changeSorting called');

                });

        });

我收到错误“ TypeError:albumFactory.changeSorting不是函数”(这是指albumFactory.changeSorting),因为我没有将其添加到工厂。我不知道该怎么做。我正在使用的html代码如下:我想调用该函数以按字母顺序对JSON文件中的内容进行排序

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
<script src="js/angular.js"></script>
<script src="js/angular-route.js"></script>
<script type="text/javascript" src="modules/app.js" ></script>

</script>
<title>
</title>

</head>
<body ng-app="albumsApp">
<div data-ng-controller="albumController">
    <!-- <ul data-ng-repeat="album in albums| orderBy:'title'"> -->
    <ul data-ng-repeat="album in albums">
    <li>
      Artist is "{{album.artist}}" and title is "{{album.title}}"

    </li>
  </ul>  
<button data-ng-click="changeSorting()">Description</button>
</div>


</body>
</html>

JSON列表如下:

{
    "albums":[    
      {
      "artist": "Arctic Monkeys",
      "title": "AM"
       },
       {
      "artist": "Nirvana",
      "title": "Nevermind"
       },
       {
      "artist": "Buck 65",
      "title": "Man Overboard"    
      }
      ]

}
蒂娜

您的视图未直接连接到Angular服务-从该视图调用的所有方法都应在您的控制器中。您应该在控制器上有一个方法,而不是在工厂中。尝试将该功能移至您的控制器:

albumsApp.controller ('albumController', function ($scope,albumFactory) {
    albumFactory.getAlbumsAsync(function(results){
        console.log('albumController async returned value');
        $scope.albums = results.albums;
    });

    $scope.changeSorting = function (){
        // your logic goes here
        console.log('changeSorting called');
    });
});

您可以将逻辑保留在控制器中。您可以orderBy在Angular的$ filter模块中使用以帮助您排序:

$filter('orderBy')(array, expression, reverse)

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章