简体   繁体   中英

How to create html page template and bind controller to it dynamically with AngularJS?

I need to create html template and bind correspondent controller to it dynamically.

How can I do it with AngularJS?

I can create dynamic template with $compile service, but I don't know how to bind a controller to it in an efficient and elegant way.

Details.

I want to create a popup menu. I made a service with a method onPopupShowEventHandler(event, data) . This method will create a simple piece of html code with some behaviour and insert it into the body of my main html code. Behaviour I'm getting from outside. And that exact behaviour depends on the situation.

So, now I'm able to create piece of html code with $compile service, but I want to put a controller into the ng-controller section of this html code. I don't know how to do it...

Code.

onPopupShowEventHandler = function(event, data) {

        var menuItems = data.popupMenuItems; // I want this elements to be accessible in 'element'

        pair = data.pair;

        var element =   '<div id="popup" style=\"' + menuStyle + '\">'+
                        '<ul>'+
                        '<li ng-repeat="item in menuItems"><a href="" ng-click="delegateInvoker($index)">{{item.name}}</a></li>'+
                        '</ul>'+
                        '</div>';

        element = angular.element(element);

        var overlayCSS = {
            left: data.clientX + offset.left + 'px',
            top: data.clientY + offset.top + 'px',
            display: 'block'
        };

            var compiled = $compile(element)($rootScope);
            compiled.css(overlayCSS);
            var body = angular.element('body');
            body.append(compiled);
};

Thanks.

您可以尝试制作指令,然后将控制器绑定到该指令,然后将该指令作为属性放入模板中。请检查此链接http://www.bennadel.com/blog/2603-directive-controller-and-link-timing- in-angularjs.htm

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