requirejs angularjs控制器未定义

时间:2017-01-04 06:29:27

标签: javascript angularjs requirejs

当我尝试动态加载控制器时,我遇到以下错误: sideCtrl&安培; P1 =未%20aNaNunction%2C%20got%20undefined

但是对于page1,代码工作正常。 这是我的代码:

main.js:

require.config({
    paths: {
        jquery: ['//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min', 'lib/jquery/jquery_2.0.0.min.js'],
        angular: ['//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min', 'lib/angular/angular_1.2.16.min'],
        angularRoute: ['//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-route.min', 'lib/angular-route/angular-route_1.2.16.min']
    },
    shim: {
        'angular' : {'exports' : 'angular'},
        'angularRoute': ['angular']
    },
    deps: ['app']
});

config.js:

define([],function(){
  function config($routeProvider) {
    $routeProvider
      .when('/page1', {
        templateUrl: 'templates/page1.html', 
        controller: 'mainCtrl'
      })
      .when('/page2', {
        templateUrl: 'templates/page2.html',         
        resolve: {
            load: function($q, $route, $rootScope) {

                var deferred = $q.defer();

                var dependencies = [
                    'sideCtrl.js'
                ];

                require(dependencies, function () {
                    $rootScope.$apply(function() {
                    deferred.resolve();
                    });
                });
                return deferred.promise;
            }
        }
      })
      .otherwise({redirectTo: '/page1'});
  }
  config.$inject=['$routeProvider'];

  return config;
});

app.js

/*global require*/
'use strict';

define([
    'angular','angularRoute', 'mainCtrl', 'config'
    ], function (angular, angularRoute,mainCtrl,config) {
        var app = angular.module('app', ['ngRoute']);
        app.config(config);
        app.controller('mainCtrl', mainCtrl);


        angular.bootstrap(document, ['app']);       
        return app; 
}); 

sideCtrl.js:

"use strict";
define(['app'], function (app) {

    app.controller('sideCtrl', ['$scope',
        function ($scope) {
            console.log("hello world");
            $scope.names="krish";
            console.log("sideCtrl calling");
        }
    ]);
    console.log(app);
    return app;
});

page2.html

<div ng-controller="sideCtrl">
 asdasdas
    {{names}}

</div>

1 个答案:

答案 0 :(得分:0)

动态添加控制器需要您使用当前活动提供程序注册它,因此您无法使用常规&#34; app.controller&#34;注册它,您需要做的是通过 $ controllerProvider.register注册它

祝你好运