我正试图通过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('...'); }
}
});
}
})();