原始代码如下:
(function() {
angular.module('test', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/test', {
templateUrl: '/templates/test.html',
controller: 'testCtrl'
})
.when('/test2', {
templateUrl: '/templates/test2.html',
controller: 'test2Ctrl'
})
.otherwise({
redirectTo: '/test'
});
});
})();
//ANOTHER FILE
(function() {
angular.module('test')
.controller('testCtrl', function($scope) {
$scope.name = "test";
})
.controller('test2Ctrl', function($scope) {
$scope.name = "test2";
});
});
没有错误,但模板中显示的所有内容都是{{name}}
,而不是范围中定义的内容。
然后我尝试将控制器移动到另一个模块中并依赖注入它。有趣的是,即使控制器被移动到一个单独的模块也不会起作用:
(function () {
angular.module('test2', []);
angular.module('test', ['ngRoute', 'test2']);
})();
//ANOTHER FILE
(function() {
angular.module('test')
.config(function($routeProvider) {
$routeProvider
.when('/test', {
templateUrl: '/templates/test.html',
controller: 'testCtrl'
})
.when('/test2', {
templateUrl: '/templates/test2.html',
controller: 'test2Ctrl'
})
.otherwise({
redirectTo: '/test'
});
});
})();
//ANOTHER FILE
(function() {
angular.module('test2')
.controller('testCtrl', function($scope) {
$scope.name = "test";
})
.controller('test2Ctrl', function($scope) {
$scope.name = "test2";
});
});
事实上,在这个问题中它引发了一个无法找到控制器的错误。
根据我的理解,这种情况正在发生,因为配置块的运行方式以及在注册控制器之前它是如何运行的。
我解决此问题的一种方法是将控制器和模板移动到指令中,然后使用指令本身作为模板。
(function() {
angular.module('test')
.config(function($routeProvider) {
$routeProvider
$routeProvider
.when('/', {
template: '<test></test>'
})
.when('/test2', {
template: '<test2></test2>'
})
.when('/test3', {
template: '<test3></test3>'
})
.otherwise({
redirectTo: '/'
});
});
})();
我想知道当你的控制器在一个单独的文件中时,是否有其他人有办法支持将控制器放入路由器。
答案 0 :(得分:1)
您可以通过这种方式组织项目
if (myDataTable != null)
{
if (myDataTable.Rows.Count > 0)
{
myRow = myDataTable.Rows[0];
}
else
{
throw new Exception("Problem obtaining data");
}
}
else
{
throw new Exception("Problem obtaining data");
}
<强> app.js 强>
templates/
test.html
test2.html
app/
app.js
controllers/
testCtrl.js
test2Ctrl.js
html文件
在html文件中添加控制器后可能不再有问题
(function() {
angular.module('test', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/test', {
templateUrl: '/templates/test.html',
controller: 'testCtrl'
})
.when('/test2', {
templateUrl: '/templates/test2.html',
controller: 'test2Ctrl'
})
.otherwise({
redirectTo: '/test'
});
});
})();
答案 1 :(得分:1)
这里的代码缺少执行它的()
......
(function() {
angular.module('test')
.controller('testCtrl', function($scope) {
$scope.name = "test";
})
.controller('test2Ctrl', function($scope) {
$scope.name = "test2";
});
});
应该是:
(function() {
angular.module('test')
.controller('testCtrl', function($scope) {
$scope.name = "test";
})
.controller('test2Ctrl', function($scope) {
$scope.name = "test2";
});
})();
答案 2 :(得分:1)
您在控制器文件中缺少()
自执行功能(IIFE)。
//ANOTHER FILE
(function() {
angular.module('test2')
.controller('testCtrl', function($scope) {
$scope.name = "test";
})
.controller('test2Ctrl', function($scope) {
$scope.name = "test2";
});
})(); //<-- added here