AngularJS - 将参数传递给Controller?

时间:2015-06-26 16:26:12

标签: javascript json angularjs model-view-controller

我正在尝试使用AngularJS创建一个简单的博客网站。我刚刚开始,所以我认为我不是最好的方法,所以欢迎任何其他建议。

我有一个带有两个博客控制器的controller.js文件。一个显示博客帖子列表,另一个显示帖子内容,包括HTML文件。

controller.js

myAppControllers.controller('BlogListCtrl', ['$scope', '$http', function ($scope, $http) {
    $http.get('articles/articles.json').success(function (articles) {
        $scope.articles = articles;
    });
}]);

myAppControllers.controller('BlogPostCtrl', ['$scope', '$routeParams', function ($scope, $routeParams) {
    $scope.includeFile = 'articles/' + $routeParams.blogPostId + '.html';
}]);

articles.json

[
{
    "id": "test-article-one",
    "title": "Test Article one",
    "author": "Gareth Lewis",
    "datePosted": "2015-06-23",
    "summary": "This is a test summary"
},
{
    "id": "test-article-two",
    "title": "Test article two",
    "author": "Gareth Lewis",
    "datePosted": "2015-06-23",
    "summary": "This is a test for article two"
}
]

app.js

when('/blog', {
            templateUrl: 'partials/blog-articles.html',
            controller: 'BlogListCtrl'
        }).
        when('/blog/:blogPostId', {
            templateUrl: 'partials/blog-post.html',
            controller: 'BlogPostCtrl'
        }).

博客-post.html

<ng-include src="'partials/header.html'"></ng-include>

<!-- Want to add title, author, datePosted information here... -->

<article class="content">
    <ng-include src="includeFile"></ng-include>
</article>

此博客列表工作正常。当我点击博客文章时,它也会提供HTML文件中的内容。但是,我希望能够在blog-post.html局部视图中重用所选文章中的titleauthordatePosted属性。最好的方法是什么?我是否需要以某种方式将它们传递给Controller然后传递给视图?我真的不想将这些传递给routeParams。或者我是否需要在articles.json上执行$ http.get并迭代查找所选文章,然后将属性值传递回视图?

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

这可能是一个角色的常见问题。您必须了解的是,每个控制器都定义了范围 ...为了在控制器之间共享数据,您仍然可以选择使用$scope.$parent$rootScope链接控制器但我会仔细使用它们。

最好使用基于单例模式的 Angular Services ,因此您可以使用它们在控制器之间共享信息,我认为这将是一种更好的方法。

我发现之前已经讨论过,这里有一些很好的例子:

AngularJS Service Passing Data Between Controllers

答案 1 :(得分:3)

你说建议是值得欢迎的,所以就这样了。

1 - 将您的所有Blog逻辑传输到服务;

2 - 提供解析路线的数据。这是在加载时间,404s等处理错误的更好方法。您可以为$routeChangeError提供一个监听器并在那里处理它;

3 - 在下面声明的服务中,您有调用数据的方法和检索服务缓存的列表的方法:

// services.js
myAppServices
    .service('BlogService', ['$http', '$q', function ($http, $q) {
        var api = {},
            currentData = {
                list: [],
                article: {}
            };

        api.getSaved = function () {
            return currentData;
        };

        api.listArticles = function () {
            var deferred = $q.defer(),
                backup = angular.copy(currentData.list);

            $http.get('articles/articles.json')
                .then(function (response) {
                    currentData.list = response;

                    deferred.resolve(response);
                }, function () {
                    currentData.list = backup;

                    deferred.reject(reason);
                });

            return deferred.promise;
        };

        api.getArticle = function (id) {
            var deferred = $q.defer(),
                backup = angular.copy(currentData.article),
                path = 'articles/' + id + '.html';

            $http.get(path, {
                cache: true
            })
                .then(function (response) {
                    currentData.article = {
                        path: path,
                        response: response
                    };

                    deferred.resolve(currentData.article);
                }, function (reason) {
                    currentData.article = backup;

                    deferred.reject(currentData.article);
                });

            return deferred.promise;
        };

        return api;
    }]);

BlogService.getSaved()将检索每次调用后生成的存储数据。

我已经制定了一种方法来调用ng-include路径,因此你可以使用cache === true验证它是否存在,浏览器会保留它的副本,当再次调用它时视图。博客文章的回复也是如此,因此您可以随时访问其路径和响应。

在下面的控制器上,他们适应了当前的需求:

// controller.js
myAppControllers
    .controller('BlogListCtrl', ['$scope', 'articles',
        function ($scope, articles) {
            $scope.articles = articles;

            /* OTHER STUFF HERE */
        }
    ])
    .controller('BlogPostCtrl', ['$routeParams', '$scope', 'article' 'BlogService',
        function ($routeParams, $scope, article, BlogService) {
            // On `article` dependency, you have both the original response
            // and the path formed. If you want to use any of it.

            $scope.includeFile = article.path;

            // To get the current stored data (if any):
            $scope.articles = BlogService.getSaved().list;

            // Traverse the array to get your current article:
            $scope.article = $scope.articles.filter(function (item) {
                return item.id === $routeParams.id;
            });

            /* OTHER STUFF HERE */
        }
    ]);

在解析路线时,路线声明已更改为加载数据。

// app.js
$routeProvider
    .when('/blog', {
        templateUrl: 'partials/blog-articles.html',
        controller: 'BlogListCtrl',
        resolve: {
            articles: ['BlogService', '$routeParams', function (BlogService, $routeParams) {
                return BlogService.listArticles();
            }]
        }
    })
    .when('/blog/:id', {
        templateUrl: 'partials/blog-post.html',
        controller: 'BlogPostCtrl',
        resolve: {
            article: ['BlogService', '$routeParams', function (BlogService, $routeParams) {
                return BlogService.getArticle($routeParams.blogPostId);
            }]
        }
    })

答案 2 :(得分:0)

您可以使用全局范围来设置此数据,也可以使用服务在控制器之间进行通信。有很多方法可以解决这个问题,请阅读下面的链接中的服务,看看你是否能找到解决问题的方法。

AngularJS: Service vs provider vs factory