我想在通过 View 加载 Controller 时添加动态 Controller 的脚本。
这是我的文件树:
- index.html
- 应用程序.js
- 观看次数
- prod.html
- cat.html
- prod.html
- Controller
- prod.js
- cat.js
我希望当用户获得 /prod/
URL 时,应用程序将加载(在 View 中) Controller 逻辑的 prod.html 和 prod.js
动态地。
当然,所有这些逻辑都需要 ng-route。
Index.html
<body data-ng-app="myApp">
<div data-ng-view=""></div>
</body>
Default.js 使用 AngularJS v1.3.14
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider, $locationProvider, $controllerProvider, $provide) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
app.registerCtrl = $controllerProvider.register;
$routeProvider.
when('/:name', {
templateUrl: function (urlAttr) {
return '/views/' + urlAttr.name + '.html';
}
});
// This code throw error:
//TypeError: undefined is not a function
//at angular.min.js:1
//at r (angular.min.js:1)
//at at (angular.min.js:1)
//at b (angular.min.js:1)
//at b (angular.min.js:1)
//at b (angular.min.js:1)
//at b (angular.min.js:1)
//at $get.t (angular.min.js:1)
//at angular.min.js:1
//at p.$get.p.$eval (angular.min.js:1)
$provide.decorator('$controller', ['$delegate', function ($delegate) {
// I want to get the controller name and than load the js file.
// return function (constructor, locals) {
// if (typeof constructor == "string") {
// locals.$scope.loadControllerScript(constructor);
// }
// return $delegate(constructor, locals);
// }
}]);
});
Prod.html
<div class="row" data-ng-controller="prodCtrl">
{{test}}
</div>
Prod.js
app.registerCtrl('prodCtrl', function ($scope) {
$scope.test = '';
});
问题是错误:“undefined is not a function”。 (参见 Default.js 中的代码)
如果问题不清楚,我很乐意解释更多。
最佳答案
您不能在配置阶段请求实例(例如 $controller)。您只能在那里访问提供商。检查docs :
Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.
更新:这有效:
var app = angular.module("myApp", ['ng'], ['$provide', function($provide) {
$provide.decorator('$controller', ['$delegate', function($delegate) {
return function(constructor, locals) {
console.log("executing custom code ...");
return $delegate(constructor, locals);
}
}])
}]);
检查这个demo
关于javascript - $provide.decorator $controller 返回 throw undefined 不是一个函数 angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28791884/