使用angularjs从json文件夹中检索数据

时间:2015-02-23 00:33:49

标签: javascript html json angularjs

你好我尝试制作一个angularjs应用程序,所以我从一个json文件夹中检索数据,但它显示了这个[“冒险”,“科幻”] 我怎么能从这个[“冒险”,“科幻”]中删除[“”]

这是我的json文件夹

[
    {
      "title": "Interstellar",
      "genre": [
        "adventure",
        "sci-fi"
      ],
      "watched": false
    },
    {
      "title": "Inception",
      "genre": [
        "action",
        "mystery",
        "sci-fi"
      ],
      "watched": true
    }
]

这是我的service.js

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


app.service('moviesService', function($http,$q){

    var deferred =$q.defer();
    $http.get('movies.json').then(function (data)
    {
        deferred.resolve(data);

        });

    this.getPlayers = function ()
    {
        return deferred.promise;
    }
})

这是我的控制器

app.controller('appcontrolles', function($scope,moviesService){
    var promise = moviesService.getPlayers();
    promise.then(function(data)
{
    $scope.players =data.data;
    console.log($scope.players);
});
})

这是我的index.html

    <table class="table table-striped">
        <thead>

            <tr>

                <th>title</th>
                <th>genre</th>
                <th>watched</th>
            </tr>

        </thead>
        <tbody>
            <tr ng-repeat="movie in players | filter : genre |filter: search.genre |filter : watched ">

                <td>{{movie.title}}</td>
                <td>{{movie.genre}}</td>
                <td><input type="checkbox" name="vu", ng-model="movie.watched",value="true"></td>
            </tr>
        </tbody>
    </table>

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

由于movie.genre是一个数组,当你刚放{{movie.genre}}时,Angular会将该值输出为表示数组的字符串:["adventure","sci-fi"]

如果你想要一个简单的以逗号分隔的值列表,你可以使用数组的.join()函数创建一个带有指定分隔符的字符串,如", ",如下所示:

<td>{{movie.genre.join(", ")}}</td>

或者,如果您想要更复杂的DOM,那么您可以ng-repeat覆盖该数组:

<td><span ng-repeat="genre in movie.genre">{{genre}}</span></td>

关闭主题:

您不需要将$q.defer用于已经返回承诺的内容,例如$http - 您可以返回该承诺,因此您的服务可以简化为:

app.service('moviesService', function($http){
    this.getPlayers = function()
    {
        return $http.get('movies.json');
    }
});
当您尝试转换某些第三方服务的非承诺异步功能时,会使用

$q.defer,例如,使用on-successon-error处理程序。