我有一个返回json数组对象的API,现在,我在我的控制器中得到了这样的json,它运行得很好:
a
但我认为这不是一个好习惯,我已经尝试过了:
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;
});
}
}])
在这种情况下,我得到未定义的值:
var result = ApiCall.GetApiCall().success(function (lyrics) {
$scope.lyrics=lyrics.data;
});
所以,如果你们能提出更好的方法,我会很感激。
答案 0 :(得分:3)
除了console.log之外,你做的是正确的事情。如果在完成赋值之前执行了日志语句,则将获得未定义的值。
另外,我不明白为什么要做var result =
你可以简单地做
ApiCall.GetApiCall('v1', 'lyrics', '1').success(function (data) {
$scope.lyrics = data.data;
console.log($scope.lyrics.id);
}).error(fucntion(data){
console.log(data);
});