【发布时间】:2014-07-17 19:24:37
【问题描述】:
我有一个工作的角度应用程序,但我想对其进行一些重组。我有一堆指令实际上并没有做任何事情,虽然整个应用程序应该被一个指令封装,但我仍然在该指令之外有两个主要的控制器声明。
我合并了这两个控制器,因为尽管它们处理不同的问题(一个处理功能数据,另一个处理导航状态),但它们都是整个应用程序所必需的。
其次,我想摆脱松散的声明并从:
<div ng-app="myApp" class="myApp" ng-cloak ng-controller="myController">
<myAppdirective ng-controller="myNavigationController"></myAppdirective>
</div>
到:
angular.module('myApp').
directive('myAppDirective', ['myController', function(myController) { {
return {
restrict: 'AE',
replace: true,
scope: true,
controller: myController,
template: '<div>' +
'<ng-include src="\'partials/navigation.html\'">' +
'<ng-view></ng-view>' +
'</div>'
};
}]);
神秘的是,这不起作用。这不应该工作吗?
我收到此错误:https://docs.angularjs.org/error/$injector/unpr?p0=myControllerProvider%20%3C-%20myController%20%3C-%20myAppDirective
我尝试在模板中使用 ngController,但这给了我 TypeError: Cannot read property 'insertBefore' of null 在 Angular 代码深处的某个地方。
我很茫然。我可能在做一些根本错误的事情。但是什么?
解决方案:我恢复了两个控制器的合并。这恢复了我最初的关注点分离,并修复了那个神秘的 TypeError。
我的指令现在看起来像这样:
(function() {
'use strict';
/*global angular */
angular.module('myApp').
directive('myAppDirective', function() {
return {
restrict: 'AE',
replace: true,
scope: true,
controller: 'myController',
template: '<div ng-controller="myNavigationController">' +
'<ng-include src="\'partials/navigation.html\'"></ng-include>' +
'<ng-view></ng-view>' +
'</div>'
};
});
})();
这似乎工作正常。
【问题讨论】:
标签: angularjs