$provide.decorator$controller return throw undefined不是angula



我想在通过视图加载控制器时添加动态控制器的脚本。

这是我的文件树:

  • index.html
  • app.js
  • 视图
    • prod.html
    • cat.html
  • 控制器
    • prod.js
    • cat.js

我希望当用户获得/prod/ URL时,应用程序将动态加载(在视图中)控制器逻辑的prod.html和prod.js
当然,所有这些逻辑都需要ng路线。

Index.html

<body data-ng-app="myApp">
  <div data-ng-view=""></div>  
</body>

默认.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 = '';
});

问题在于错误:"未定义不是函数"。(请参阅Default.js中的代码)
如果问题不清楚,我很乐意解释更多

在配置阶段不能请求实例(例如$controller)。您只能访问那里的提供程序。检查文档:

配置块-在提供程序注册和配置阶段执行。仅提供程序和常量可以注入到配置块中。这是为了防止服务完全实例化之前的意外实例化已配置。

更新:这是有效的:

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);
        }
    }])
}]);

检查此演示

相关内容

最新更新