简体   繁体   中英

Use a modal ng-controller as a regular controller

I have a controller used by a modal view (with angularui). At some point I would like to use this controller with a custom view (not a modal one). So everything is fine except for the resolve variables (variables sent to the controller).

I call the modal like this:

    var modalInstance = $modal.open({
        templateUrl: 'myModal.html',
        controller: 'modalCtrl',
        size: 'lg',
        resolve: {
            variable: function(){
                return myVar;
            }
        }
    });

How can I send variables from javascript (or html)?

Here is how I bootstrap my custom view (custom.html):

angular.element($(document.body)[0].children[0]).attr('ng-controller','modalCtrl');
angular.bootstrap( document.body, [ 'myApp' ]);

One way to do this would be to define a service or a value with the same name of your resolve ( variable in this case). Then Angular will find the dependency for you and inject it.

You may not want to always have this service/value defined. So you might define this service/value in a module, and then conditionally load that module when you bootstrap the app:

if (someCondition) {
  angular.module('use.me.conditionally', []).value('variables', 123);
  angular.element($(document.body)[0].children[0]).attr('ng-controller','modalCtrl');
  angular.bootstrap(document.body, ['myApp', 'use.me.conditionally']);
} else {
  angular.bootstrap(document.body, ['myApp']);
}

EDIT:

You can use the value() or service() functions to declare injectable objects that have many properties:

var foo = { property1: 'abc', property2: 456 };
angular.module('use.me.conditionally',[])
    .value('variablesAsAValue', foo)
    .service('variablesAsAService', function() { return foo; });

Note that you don't need both value() and service() , I'm just showing both approaches. value() is typically used for constant type of variables, and services are typically object/classes.

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