简体   繁体   中英

Angular load custom controller

Is it possible to load a custom controller specifying the filename each partial in angularjs?

Something like this:

 var demo = angular.module('demo', ['ngRoute', 'ui.bootstrap', 'demo.filters', 'demo.services', 'demo.directives', 'demo.controllers'])

    .config(['$routeProvider', function ($routeProvider) {


        $routeProvider.when('/custom', 
                   {
                      templateUrl: 'partials/custom.html', 
                      controller:   customController.js
                    });

    });

With the way require js works you need to set your app up like this:

var demo = angular.module('demo', ['ngRoute', 'demo.filters', 'demo.services', 'demo.directives']);

demo.config(['$routeProvider',
  function($routeProvider) {
    var _routes = ['/custom', '/custom2'];
    _routes.map(function(route) {
      var _cntrlName = route.slice(1, route.length);
      require([_cntrlName + "Controller"], function(controller) {
        $routeProvider.when(route, {
          templateUrl: '.' + route + '.html',
          controller: controller
        });
      });
    });
  }
]);

And your controller code must look like this:

define(function(require, exports, module) {
  function controller($scope) {
    $scope.testvar = "test 1!";
  }
  module.exports = controller;
});

Here is a plunker to demonstrate this http://plnkr.co/edit/N5fE5rezf6eM8jDIz23w?p=info

Angular is not able to load JS files, but you can do this with RequireJS

var demo = angular.module('demo', ['ngRoute', 'ui.bootstrap', 'demo.filters', 'demo.services',     'demo.directives'])

demo.config(['$routeProvider', function ($routeProvider) {
    var _routes = ['/custom', '/somepage']

    _routes.map(function(route){
        var _cntrlName = route.slice(1, route.length);
        $routeProvider.when(route,{
             templateUrl: 'partials' + route;
             controller: require('./' + _cntrlName + 'Controller.js');
        })     
    })  
});

Controller file:

(function(){
   function customController($scope){
       console.log($scope);   
   };
   return 'customController';  
)()

Instead of specifying a file put the controller's name. However, you should remove ng-controller directive from your partial.

Yes. you can load the other controller scope inside a different controller.

Sample Code :
var mode = angular.module().config(function(){

controller("controllerName",{$scope : scope}); // This line is important

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM