AngularJS fromJson返回字符串?

时间:2013-11-17 16:47:05

标签: jquery ajax json angularjs local-storage

我正在尝试AngularJS的UI-Router用于嵌套视图,这似乎正在起作用。但是,在第97行中,您将找到一个解决方案,它会延迟嵌套视图的初始化,直到接收和处理数据为止。

您会注意到我正在将json Feed捕获到localStorage(第123行)。我使用它来保存每个帖子的副本以进行快速数据检索和UI绑定,而不必等待第二个Ajax请求来检索该数据。

问题

如果单击,从ajax请求返回的任何链接,将显示嵌套视图。填充视图的数据似乎已完全转换为文本。没有HTML标记呈现为HTML ...一个完整的字符串。

诊断

我不确定是什么原因造成的。可能是因为我使用jQuery Ajax调用来检索那些信息吗?

我之前尝试过使用Angular自己的$http.jsonp,但我一直得到一个我无法弄清楚的类型错误......所以也许只有数据“它”才能获取?我个人想在这个小应用程序中抛弃jQuery,但它似乎唯一的选择是为我检索数据没有问题。

请求

希望将绑定到最终嵌套视图的数据呈现为HTML,而不是字符串。谢谢! jsFiddle:http://jsfiddle.net/halkibsi/Z5aEs/11/

注意

此应用程序的第3级嵌套视图未在Firefox中显示,仅适用于Chrome和Safari浏览器。没有在IE或Opera中测试。

    // LOAD MODULES
    angular.module('myApp', ['ui.router'])
.run([ '$rootScope', '$state', '$stateParams', function ($rootScope, $state, $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
  }]);


    /*************************/
    // STATES
    /*************************/
    angular.module('myApp')
    .config( ['$stateProvider', '$urlRouterProvider', function ( $stateProvider, $urlRouterProvider ) {

    /***************************/
    // Redirects and Otherwise //
    $urlRouterProvider
        .when('/en', '/en/news')
        .otherwise('/');


    /************************/
    // State Configurations //
    $stateProvider

        /********/
        // HOME //
        /********/
        .state('home', {
            url: '/',
            template: 
                '<div>'+
                '<header class="section-title"><h1>HOME</h1></header>'+
                '<ul class="nav">'+
                '<li ng-class="{ active: $state.includes(\'arabic\') }"><a ui-sref="arabic">عربي</a></li>'+
                '<li ng-class="{ active: $state.includes(\'english\') }"><a ui-sref="english">English</a></li>'+
                '</ul>'+
                '</div>',
        })

        /**********/
        // ARABIC //
        /**********/
        .state('arabic', {
            url: '/ar',
            //abstract: true,
            template:
                '<div dir="rtl">'+
                    '<header class="section-title"><h1>الواجهة العربية</h1></header>'+
                    '<ul class="nav">'+
                        '<li ng-class="{ active: $state.includes(\'home\') }"><a ui-sref="home">الصفحة الرئيسية</a></li>'+
                        '<li ng-class="{ active: $state.includes(\'english\') }"><a ui-sref="english">English Interface</a></li>'+
                        '<li><a href="#/ar/ndc-news">أخبار</a></li>'+
                        '<li><a href="#/ar/ndc-photos">صور</a></li>'+
                        '<li><a href="#/ar/ndc-videos">فيديو</a></li>'+
                        '<li><a href="#/ar/ndc-podcasts">صوتيات</a></li>'+
                    '</ul>'+
                    '<!-- MAIN UI VIEW FOR THIS TEMPLATE -->'+
                    '<div ui-view ng-animate="{enter:\'fade-enter\'}"></div>'+
                '</div>',
        })

        /***********/
        // ENGLISH //
        /***********/
        .state('english', {
            //abstract: true,
            url: '/en',
            template:
                '<div>'+
                    '<header class="section-title"><h1>English Interface</h1></header>'+
                    '<ul class="nav">'+
                        '<li ng-class="{ active: $state.includes(\'home\') }"><a ui-sref="home">Home</a></li>'+
                        '<li ng-class="{ active: $state.includes(\'arabic\') }"><a ui-sref="arabic">الواجهة العربية</a></li>'+
                        '<li ng-class="{ active: $state.includes(\'english.news\') }"><a ui-sref="english.news">News</a></li>'+
                        '<li ng-class="{ active: $state.includes(\'english.photos\') }"><a ui-sref="english.photos">Photos</a></li>'+
                        '<li ng-class="{ active: $state.includes(\'english.videos\') }"><a ui-sref="english.videos">Videos</a></li>'+
                        '<li ng-class="{ active: $state.includes(\'english.podcasts\') }"><a ui-sref="english.podcasts">Podcasts</a></li>'+
                    '</ul>'+
                    '<!-- MAIN UI VIEW FOR THIS TEMPLATE -->'+
                    '<div ui-view ng-animate="{enter:\'fade-enter\'}"></div>'+
                '</div>',
        })

            // English -> NDC News
            .state('english.news', {
                url: '/news',
                template:
                    '<header class="section-title"><h2>News</h2></header>'+
                    '<ul>'+
                      '<li ng-repeat="post in posts"><a ui-sref="english.news.single({postId:post.id})">{{ post.title }}</a></li>'+
                    '</ul>'+
                        '<div style="margin: 0 0 0 2em;">'+
                        '<!-- MAIN UI VIEW FOR THIS TEMPLATE -->'+
                        '<div class="ui-view-lev2" ui-view></div>'+
                    '</div>',
                resolve: {
                    news: function() {
                            return $.ajax({
                                type: "GET",
                                url: "http://ndcye.org/api/get_posts/?post_type=post&cat=3&callback=?",
                                dataType: "jsonp",
                                success: function(response){
                                    //console.log(response);

                                    var newsList = [];
                                    for ( var i=0; i < response.posts.length; i++) {

                                        var id = response.posts[i].id;
                                        var title = response.posts[i].title;
                                        var thumbnail = response.posts[i].thumbnail_images.mobile.url;
                                        var excerpt = response.posts[i].excerpt;
                                        var content = response.posts[i].content;

                                        // SAVE POST AS AN OBJECT
                                        var post_object = {
                                            id: id,
                                            title: title,
                                            thumbnail: thumbnail,
                                            excerpt: excerpt,
                                            content: content,
                                        };
                                        if (localStorage.getItem( 'post_object_'+id ) === null) {
                                            localStorage.setItem( 'post_object_'+id, angular.toJson(post_object) );
                                        }

                                        newsList.push(post_object);
                                    }

                                    localStorage.setItem( 'ndc_news', angular.toJson(newsList) );
                                    console.log( newsList );
                                },
                                error: function(){
                                    console.log("error!");
                                }
                            });
                    }
                },
                controller: ['news', '$scope', '$state', function (news, $scope, $state) {
                    $scope.posts = news.posts;
                    console.log($scope.posts);
                }], // controller end
            })

                // English -> NDC News Single
                .state('english.news.single', {
                    url: '/{postId:[0-9]{1,4}}',
                    template:
                        '<header class="section-title"><h3>{{ singlePost.title }}</h3></header>'+
                        '<div>{{ singlePost.content }}</div>',
                    controller: ['$scope', '$state', '$stateParams', function ($scope, $state, $stateParams) {
                        var singlePost = '';
                        singlePost = angular.fromJson( localStorage.getItem( 'post_object_' + $stateParams.postId ) );

                        $scope.singlePost = singlePost;
                        console.log( singlePost );
                    }]
                })








            // English -> NDC Photos
            .state('english.photos', {
                url: '/photos',
                template:
                    '<header class="section-title"><h2>Photos</h2></header>'+
                    'Photo albums go here',
            })

            // English -> NDC Videos
            .state('english.videos', {
                url: '/videos',
                template:
                    '<header class="section-title"><h2>Videos</h2></header>'+
                    'YouTube playlists go here',
            })

            // English -> NDC Podcasts
            .state('english.podcasts', {
                url: '/podcasts',
                template:
                    '<header class="section-title"><h2>Podcasts</h2></header>'+
                    'Podcast playlists go here',
            })



  } // end function ($stateProvider,   $urlRouterProvider)

    ]) // end .CONFIG
    ; // ens STATES

1 个答案:

答案 0 :(得分:3)

该计划存在两个问题:

  1. 您正在使用{{ ... }}singlePost.content绑定到HTML。这必然会逃避HTML
  2. 仅使用ng-bind-html="singlePost.content"无效,因为角度现在只会呈现trusted HTML
  3. 所需的唯一更改是 english.news.single

    .state('english.news.single', {
      url: '/{postId:[0-9]{1,4}}',
      template:
              '<header class="section-title"><h3>{{ singlePost.title }}</h3></header>'+
              '<div ng-bind-html="content"></div>',
      controller: ['$scope', '$state', '$stateParams', '$sce', function ($scope, $state, $stateParams, $sce) {
              var singlePost = '';
              singlePost = angular.fromJson( localStorage.getItem( 'post_object_' + $stateParams.postId ) );
    
              $scope.singlePost = singlePost;
              $scope.content = $sce.trustAsHtml(singlePost.content);
              console.log( singlePost );
      }]
    })
    

    工作示例:http://jsfiddle.net/Z5aEs/12/

    旁注:它也适用于Firefox 25。