【问题标题】:unable to view data redirected using $routeParams in angular无法使用角度中的 $route 参数查看数据重定向
【发布时间】:2017-09-02 20:47:03
【问题描述】:

我有一些 json 格式的数据,想在我的 html 页面中查看它,我为此使用了 $routeParams,但无法从 json 文件中获取数据。 我创建了一个这样的控制器:

    angular.module('app.controllers', [
    'app.directives'
])
    .controller('PostController', ['$scope', '$http', function ($scope, $http){
        $http.get('data/posts.json').then(function (data) {
            $scope.posts = data.data;
        });
    }])
    .controller('SinglePostController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
        $http.get('data/posts.json').then(function (data){
            $scope.post = data[$routeParams.id];
        });
    }]);

配置如下:

angular.module('app', [
    'ngRoute',
    'app.controllers'
])
    .config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/',{
            templateUrl : 'views/post.html',
            controller : 'PostController'
        }).when('/post/:id', {
            templateUrl: 'views/singlepost.html',
            controller: 'SinglePostController'
        }).otherwise({
            redirectTo : '/'
        });
    }]);

需要获取数据的html页面是:

<h1>{{post.title}}</h1>
<p>{{post.content}}</p>

救命!

【问题讨论】:

  • 你是在循环遍历html中的数据吗?
  • 是的循环数据!
  • 你会帮忙吗?
  • 当你console.log $scope.posts 是控制台中显示的数据吗?
  • 是的,对象已显示!

标签: angularjs routeparams


【解决方案1】:

您可能需要在执行 http.get 之前声明范围变量,即

.controller('SinglePostController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
      $scope.post = {};  
      $http.get('data/posts.json').then(function (data){
            $scope.post = data.data[$routeParams.id];
        });

【讨论】:

    猜你喜欢
    • 2017-03-30
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 2020-03-01
    相关资源
    最近更新 更多