我想在需要时动态加载控制器,而不是一次性加载它们。因此,对于我实施的动态方法,它可以正常工作而不会出现任何错误。它也适用于Ui-Router。 但问题出在Index.html页面中。我想把全局(超级父)控制器名称" appCtrl"。因为这个appCtrl应该在我运行我的应用程序时初始化。为此,我需要像ng-controller =" appCtrl"或者ng-controller =" appCtrl as vm"身体标签。
但是当我这样做时,它给出错误,即appCtrl是一个函数,未定义。我试过了方法,但仍无法确定确切的错误。我已经在这个问题上工作了两到三天但仍然无法识别它。
我做了这个plunker。
查看index.html的body标签。
main.js
require.config({
paths: {
"angular": "//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0-rc.1/angular",
"ui-router": "//rawgit.com/angular-ui/ui-router/0.2.15/release/angular-ui-router"
},
shim: {
"angular": {
exports: 'angular'
},
"ui-router": {
deps: ['angular']
}
}
});
define(
['angular',
'app',
'controllers/appCtrl'],
function (angluar, app) {
angular.bootstrap(document, ['MyApp'])
});
app.js
define([
'angular',
'ui-router'
], function (angular) {
var app = angular.module('MyApp', ['ui.router']);
function lazy () {
var self = this;
this.resolve = function (controller) {
return {
ctrl: ['$q', function ($q) {
var defer = $q.defer();
require(['controllers/' + controller], function (ctrl) {
app.register.controller(controller, ctrl);
defer.resolve();
});
return defer.promise;
}]
};
};
this.$get = function (){
return self;
};
}
function config ($stateProvider, $urlRouterProvider,
$controllerProvider, $compileProvider,
$filterProvider, $provide, lazyProvider) {
$stateProvider
.state("home", {
url: "/",
controller: 'homeCtrl',
controllerAs: 'vm',
templateUrl: 'views/homeView.html',
resolve: lazyProvider.resolve('homeCtrl')
});
app.register = {
controller: $controllerProvider.register,
directive: $compileProvider.directive,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service,
constant: $provide.constant
};
}
app.provider('lazy', lazy);
app.config(config);
return app;
});
的index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.17/require.js" data-main="main.js"></script>
</head>
<body ng-controller="appCtrl as vm"> // I want this to work correctly but it is not getting loaded dynamically. I don't know why. Help me to resolve it.
<a ui-sref="home">go home</a>
<ui-view></ui-view>
{{vm.appVar}}
</body>
</html>
答案 0 :(得分:0)
您实际上在控制器代码中缺少控制器语句。 使用以下代码
define(['app'], function (app){ //Updated Line
console.log('app controller loaded');
app.controller('appCtrl',ctrl); //New Line added
ctrl.$inject = ['$http'];
function ctrl ($http) {
this.appVar = 'hi from appCtrl';
};
return ctrl;
});
请参阅plunker