Reputation: 3340
I receive from my rest api news with the specified 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.
My .when
code:
.when('/displaynews/:id',{
templateUrl: 'views/display.html',
controller: 'NewsDisplayController',
constollerAs: 'displaydash'
})
and the 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:
Object { id="56f1ba6b275c8aa5bf4895d8", title="Tytul", text="Text", more...}
How can I display this in my html template?
I try to display in html file in this way:
<p>{{news.title}}</p>
<p>{{news.text}}</p>
But it's not working
Upvotes: 1
Views: 2072
Reputation: 7578
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:
<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
Upvotes: 2
Reputation: 14591
If result.data
is an object, enclose it with square brackets and set as news
, otherwise use it directly.
displaydash.news = typeof(result.data) == "object"?[result.data]: result.data;
Upvotes: 1