AngularJS-将参数传递到控制器吗?

加雷斯·刘易斯

我正在尝试使用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';
}]);

article.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'
        }).

blog-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文件O​​K中的内容。不过,我希望能够重用titleauthordatePosted从博客,post.html局部视图所选文章属性。最好的方法是什么?我是否需要以某种方式将它们传递给Controller,然后传递给视图?我真的不想将这些作为routeParams传递。还是我需要在articles.json上执行$ http.get并进行遍历以找到所选的文章,然后将属性值传递回视图?

谢谢您的帮助。

马特斯·莱昂(Mateus Leon)

您说的建议值得欢迎,所以就去了。

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

2-提供有关解决路线的数据这是处理加载时间,404等期间错误的更好方法。您可以$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);
            }]
        }
    })

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

AngularJS:将参数从控制器传递到服务

将参数从控制器传递到angularjs中的服务

在angularjs中将多个参数从控制器传递到工厂

您可以在创建时将参数传递给AngularJS控制器吗?

从angularJs控制器将多个参数传递到Web API 2

AngularJS-从自定义指令将参数从ng-repeat传递到控制器

将参数传递给AngularJS控制器方法

将URL参数传递给AngularJS控制器?

将值从工厂传递到控制器angularJS

将数据从控制器传递到$ uibModal控制器angularjs

AngularJS:在控制器之间传递参数

AngularJS:在控制器之间传递参数

在AngularJS中将参数从视图传递到控制器到工厂

如何将参数从AngularJS指令传递给AngularJS控制器函数

AngularJs-将值从视图传递到控制器,然后传递给服务

我们如何将结果数据从 CodeIgniter 控制器传递到 AngularJS 控制器?

AngularJS,将参数传递给另一个控制器

AngularJS将指令模板中的参数传递给控制器

AngularJS:如何通过ng-href将多个参数传递给控制器?

如何将数据从EJS模板传递到AngularJS控制器

如何将URL从视图传递到Angularjs控制器文件?

如何将函数处理程序从控制器传递到AngularJs的指令隔离范围中?

如何使用angularjs将$ scope变量从控制器传递到指令

如何将功能从工厂传递到控制器angularJS

AngularJS如何将数据从控制器传递到指令

将值从提供者传递到angularJs的控制器

AngularJS:如何将数据从指令传递到控制器函数

如何将响应从服务传递到控制器Angularjs?

将AngularJS范围变量从指令传递到控制器的最简单方法?