angularjs - Iterating over JSON properties -
i have used $http
service in angular pull json object server using api. able display values so...
<div ng-controller="apicontroller apictrl"> {{apictrl.api.status}} {{apictrl.api.meta.count}} {{apictrl.api.data[0].nickname}} {{apictrl.api.data[0].account_id}} </div>
this displays values correctly unable display keys. read around, here , here. explained there ng-repeat set iterate through object , pull keys
, values
it.
<div ng-controller="apicontroller apictrl"> <div> <div ng-repeat="(key, value) in api"> {{key}} : {{value}} </div> </div> </div>
for reference apicontroller
function apicontroller($http) { var vm = this; vm.api = []; $http.get('...').success(function (data) { vm.api = data; }); };
this json requested
{ "status": "ok", "meta": { "count": 1 }, "data": [ { "nickname": "mitcha47", "account_id": 1001356515 } ] }
the second method ng-repeat="(key, value) in api"
not work , shows * ngrepeat: (key, value) in api * in html
im quite confused why doesn't work , not sure if incorrect use of syntax or not understanding how ng-repeat works.
edit
after changing div ng-repeat="(key,value) in apictrl.api" produced ->
status : ok meta : {"count":1} data : [{"nickname":"mitcha47","account_id":1001356515}]'
which okay, not format put table, next step. fixed using .fromjson
function?
do include apictrl because multiple controllers can used in each module , keeps pointing correct values?
you need specify controller in ng-repeat.
edit
according docs, when use controller as
declaration methods , properties bound directly controller instead of using $scope hence why need specify controller because api
object property of controller.
i've changed snippet show data in table unsure want display. please provide example?
<div ng-repeat="(key, value) in apictrl.api">
angular.module("app", []) .controller("apicontroller", apicontroller); function apicontroller($http) { var vm = this; vm.api = { status: "good", meta: { count: 42 }, data: [{ nickname: "timmy", account_id: 1 }, { nickname: "johnny", account_id: 2 }] }; };
table { border-collapse: collapse; } th, td { border: 1px solid black; padding: 5px; } th { text-align: left; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script> <div ng-app="app"> <div ng-controller="apicontroller apictrl"> {{apictrl.api.status}} {{apictrl.api.meta.count}} {{apictrl.api.data[0].nickname}} {{apictrl.api.data[0].account_id}} </div> <hr> <div ng-controller="apicontroller apictrl"> <div> <table> <thead> <tr> <th ng-repeat="(key, value) in apictrl.api">{{key}}</th> </tr> </thead> <tbody> <td ng-repeat="(key, value) in apictrl.api"> {{value}} </td> </tbody> </table> </div> </div> </div>
Comments
Post a Comment