我试图找出如何使用angularjs构建SPA。我的路线正常工作,每个部分页面都正确加载在ng-view中。我试图加载外部json数据。我有它的工作,但我无法弄清楚我做错了什么。目标是列出产品并为每个产品提供详细信息页面。任何帮助将不胜感激。这是我的代码:
app.js
var myApp = angular.module('app', ['ngRoute']);
myApp.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) {
$routeProvider.
when('/home',{
templateUrl: 'partials/home.html',
controller: "storeCtrl"
}).
when('/about',{
templateUrl: 'partials/about.html',
controller: "storeCtrl"
}).
when('/computers',{
templateUrl: 'partials/computers.html',
controller: "storeCtrl"
}).
when('/smartphones',{
templateUrl: 'partials/smartphones.html',
controller: "storeCtrl"
}).
when('/tablets',{
templateUrl: 'partials/tablets.html',
controller: "storeCtrl"
}).
otherwise({
redirectTo: '/home'
});
}]);
myApp.controller('storeCtrl', ['$scope', '$http', function($scope, $http) {
$scope.homeHeading = 'Home';
$scope.aboutHeading = 'About Us';
$scope.computersHeading = 'Computers';
$scope.smartphonesHeading = 'Smartphones';
$scope.tabletsHeading = 'Tablets';
$http.get('products.json').success(function(data) {
$scope.products = data;
});
console.log($scope.products);
}]);
computers.html
<div ng-controller="storeCtrl">
<h1>{{computersHeading}}</h1>
<div ng-repeat="item in products">
<p>{{ item.name }}</p>
</div>
</div>
答案 0 :(得分:0)
你应该试试这个
$http.get('products.json').then(function(result) {
$scope.products = result.data;
});
并从视图中删除ng-controller,因为您已在myApp.config()
中对其进行了定义答案 1 :(得分:0)
尝试使用返回promise对象的$http.get
服务。