Emad Dehnavi Emad Dehnavi - 1 year ago 73
AngularJS Question

Best practice to get a json response object in angularjs

I have an API which return a json array object, right now, I get the json in my Controller like this and it works just fine :

angular.module('lyricsApp', [])
.controller('LyricsController', ['$scope', 'ApiCall', function ($scope, ApiCall) {
$scope.lyrics = {
id: "",
songName: "",
singerName: "",
writtenBy: "",
lyricText: "",
isEnable: "",
created_at: "",
updated_at: ""

$scope.searchLyric = function () {
var result = ApiCall.GetApiCall().success(function (lyrics) {
$scope.lyrics.id = lyrics.data.id
$scope.lyrics.singerName = lyrics.data.singerName;
$scope.lyrics.songName = lyrics.data.songName;
$scope.lyrics.writtenBy = lyrics.data.writtenBy;
$scope.lyrics.lyricText = lyrics.data.lyricText;
$scope.lyrics.isEnable = lyrics.data.isEnable;
$scope.lyrics.created_at = lyrics.data.created_at;
$scope.lyrics.updated_at = lyrics.data.updated_at;

But I think this is not a good practice, I already try this :

var result = ApiCall.GetApiCall().success(function (lyrics) {

in this case I get undefined value :

console.log($scope.lyrics.id); // show Undefined

So, if you guys can suggest a better way I will be appreciate it.

Answer Source

You are doing the right thing, except for console.log. If your log statement is executed before the assignment is done, you will get the undefined value.

Also I don't see why you would do a var result =

You can simply do

ApiCall.GetApiCall('v1', 'lyrics', '1').success(function (data) {
    $scope.lyrics = data.data;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download