我刚开始使用 AngularJS,在使用 {{ expressions }} 从 JSON 中提取数据时遇到了问题,我使用 $http.get 获取了这些数据。 JSON 对象运行良好,因为我能够将其记录到控制台。但是当我尝试在我的 view.html 中显示它时,表达式是空的。也许这只是一些小事,但我想不通。
下面的代码片段
路由片段:
$routeProvider
.when('/contacts/:contactId', {
controller: 'ContactController',
templateUrl: 'js/views/contact.html'
})
.otherwise({
redirectTo: '/'
});
Controller :
app.controller('ContactController', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
$http.get($routeParams.contactId + '.json').success(function(data) {
$scope.detail = data;
})
.error(function(data) {
return data;
console.log("Failed to get data")
});
$scope.pageClass = 'contact-screen';
}]);
contact.html View 的一部分:
<div class="text-container">
<h2 class="name"> {{ detail.name }} </h2>
<h3 class="subtitle"> "{{ detail.subtitle }}" </h3>
</div>
最佳答案
您有一个包含数据对象的数组,而不是您的代码当前指示的单个对象。
只显示当前 View 中的一项:
$scope.detail = data[0];
但由于您可能会有多个 Controller ,所以 Controller 保持不变并使用 ng-repeat
遍历数组
<div class="text-container" ng-repeat="item in detail">
<h2 class="name"> {{ item.name }} </h2>
<h3 class="subtitle"> "{{ item.subtitle }}" </h3>
</div>
或者,因为您在 url 中有 :contactId
,更改后端以返回单个对象并保持您的代码完全相同
关于javascript - AngularJS - 无法显示来自 JSON 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31466364/