在AngularJS应用程序中使用封装指令和路由的推荐方式是什么

What is the recommended way to use an encapsulated directive and routing within an AngularJS app?

本文关键字:路由 是什么 方式 指令 应用程序 AngularJS 封装      更新时间:2023-09-26

我正试图通过AngularJs 1.5应用程序采用最佳实践。已经跟随Todd Motto和John Papa的风格指南

问题是:我的应用程序有使用ngRoute的路由。所以,这个:

function RoutingConfig($routeProvider) {
    $routeProvider
        .when('/route1', {
            controller: 'Ctrl1 as vm',
            templateUrl: 'partials/route1.html',
            resolve: { myCoolService: myCoolService } // to abbreviate
        })
        .when('/route2', {
            controller: 'Ctrl2 as vm',
            templateUrl: 'partials/route2.html'
        })
        .otherwise({redirectTo: '/route1'}):
}
angular
    .module('myApp', ['ngRoute'])
    .config(RoutingConfig);

好的。到目前为止,一切都很好。

现在,让我们说,在我的Angular 2之路中,我想采用将所有内容封装在指令中方法。通过这种方式,我将使用AngularJS 1.5创建类似于的web组件

如果我遵循正确的做法,我可以为我的路由1创建一个指令,并直接为该指令定义一个控制器:

function MyCoolDirective() {
    var directiveDefObj = {
        controller: Ctrl1,
        controllerAs: 'vm',
        scope: {
            data: "=",
        },
        bindToController: true, // isolated scope
        link: linkFnc // just declared to abbreviate
    };
    return directiveDefObj;
}

angular
    .module('myApp')
    .directive('MyCoolDirective', MyCoolDirective);

那么,我应该在哪里声明控制器?在路由配置中?在每个指令中听起来有点多余。

使用您的示例,这是我如何处理指令中的控制器,如papa风格的指南

如上所述,我建议在准备角2时检查新的角1.5分量方法。https://docs.angularjs.org/guide/component

(function () {
    angular
        .module('AppName')
        .directive('directiveName', directiveName)
        .config(routeConfig);
    directiveName.$inject = ['$compile'];
    function directiveName($compile) {
        return {
            scope: {
                customAttribute: '=',
            },
            link: directiveLink,
            controller: directiveController
        };
        function directiveLink(scope) {
        }
        function directiveController($scope) {
        }
    }
    routeConfig.$inject ['$routeProvider'];
    function routeConfig($routeProvider) {
        $routeProvider.when('/home', {
            template: '<custom-directive></custom-directive>',
            resolve: {
                user: function($http) { return $http.get('...'); }
            }
        });
    }
})();