AngularJS - 无法显示来自 JSON 的内容
AngularJS - Can't Display Content from JSON
我刚从 AngularJS 开始,在使用 {{ 表达式 }} 从 JSON 中提取数据时遇到问题,而我是通过 $http.get 获取的。 JSON 对象运行良好,因为我能够将它记录到控制台。但是当我尝试在 view.html 中显示它时,表达式是空的。可能是小事,我想不通。
下面的代码片段
路由代码段:
$routeProvider
.when('/contacts/:contactId', {
controller: 'ContactController',
templateUrl: 'js/views/contact.html'
})
.otherwise({
redirectTo: '/'
});
控制器:
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 视图的片段:
<div class="text-container">
<h2 class="name"> {{ detail.name }} </h2>
<h3 class="subtitle"> "{{ detail.subtitle }}" </h3>
</div>
您有一个包含数据对象的数组,而不是您的代码当前指示的单个对象。
要仅显示您当前查看的一项:
$scope.detail = data[0];
但由于您可能会有多个控制器,因此请保持不变并使用 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
,请将后端更改为 return 单个对象并保持代码不变
我刚从 AngularJS 开始,在使用 {{ 表达式 }} 从 JSON 中提取数据时遇到问题,而我是通过 $http.get 获取的。 JSON 对象运行良好,因为我能够将它记录到控制台。但是当我尝试在 view.html 中显示它时,表达式是空的。可能是小事,我想不通。
下面的代码片段
路由代码段:
$routeProvider
.when('/contacts/:contactId', {
controller: 'ContactController',
templateUrl: 'js/views/contact.html'
})
.otherwise({
redirectTo: '/'
});
控制器:
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 视图的片段:
<div class="text-container">
<h2 class="name"> {{ detail.name }} </h2>
<h3 class="subtitle"> "{{ detail.subtitle }}" </h3>
</div>
您有一个包含数据对象的数组,而不是您的代码当前指示的单个对象。
要仅显示您当前查看的一项:
$scope.detail = data[0];
但由于您可能会有多个控制器,因此请保持不变并使用 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
,请将后端更改为 return 单个对象并保持代码不变