From an AngularJS controller, how do I resolve another controller function defined in the module (dynamic ng-controller)?

前端 未结 2 1661
执念已碎
执念已碎 2021-01-15 06:58

Self explanatory fiddle: http://jsfiddle.net/5FG2n/6/

I need to dynamically choose the controller to use at runtime based on its name as a string. The string will b

2条回答
  •  日久生厌
    2021-01-15 07:36

    You don't need to dynamically choose the controller. Use a single controller and use DI to provide different functionality to that controller.

    angular.module('app', [])
        .service('ControllerService', function() {
            this.get = function(controllerName) {
                // ... do your logic for returning the controller functionality here
                if (controllerName == "fooController") {
                    return {
                        foo: function() { return "foo" }
                    }
                }
                else {
                    return {
                        foo: function() { return "bar" }
                    }
                }
            });
        })
        .controller('SingleController', ['$scope', 'ControllerService',
            function($scope, ControllerService) {
                $scope.functionality = ControllerService.get('fooController');
            });
    

    You bind to the functionality object on your controller:

    {{functionality.foo()}}

提交回复
热议问题