简体   繁体   English

AngularJS显示一个json对象

[英]AngularJS display one json object

I receive from my rest api news with the specified id. 我从我的api新闻中收到了指定的id。 When I display all news I used ng-repeat and works fine but when I want display one object this method is not working. 当我显示我使用ng-repeat所有新闻并且工作正常但是当我想显示一个对象时,这种方法不起作用。

My .when code: 我的.when代码:

.when('/displaynews/:id',{
    templateUrl: 'views/display.html',
    controller: 'NewsDisplayController',
    constollerAs: 'displaydash'
})

and the controller : controller

.controller('NewsDisplayController',
    function($routeParams, NewsModel){

      var displaydash = this;
      var newsId = $routeParams.id;
      path = 'getNewsById/'+newsId;

      function getNewsById() {
          NewsModel.getNewsById().then(function (result){
              displaydash.news = result.data;
              console.log(displaydash.news);
          })
      }

      getNewsById();
})

Result from console.log: 来自console.log的结果:

Object { id="56f1ba6b275c8aa5bf4895d8",  title="Tytul",  text="Text",  more...}

How can I display this in my html template? 如何在我的html模板中显示这个?

I try to display in html file in this way: 我尝试以这种方式在html文件中显示:

<p>{{news.title}}</p>
<p>{{news.text}}</p>

But it's not working 但它不起作用

You can go for : 你可以去:

angular.toJson(JSONObj);

So, here you can go for: in Controller: 所以,在这里你可以去:在控制器:

displaydash.news = result.data;
$scope.news      = angular.toJson(displaydash.news);

in HTML: 在HTML中:

<p>{{news}}</p>

The issue in your question is simple, you are trying to access news object which you have not defined, try creating a scope variable for it, you will be easily able to access it: 您的问题中的问题很简单,您正在尝试访问尚未定义的新闻对象,尝试为其创建范围变量,您将可以轻松访问它:

 $scope.displaydash.news = result.data;

<p>{{displaydash.news.title}}</p>
<p>{{displaydash.news.text}}</p>

Refer: https://docs.angularjs.org/api/ng/function/angular.toJson 参考: https//docs.angularjs.org/api/ng/function/angular.toJson

如果result.data是一个对象,请用方括号括起来并设置为news ,否则直接使用它。

 displaydash.news = typeof(result.data) == "object"?[result.data]: result.data;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM