Dynamically Loading Controllers and ng-include

前端 未结 3 500
夕颜
夕颜 2021-01-31 16:57

At the moment I have an app that has a sidebar, and the sidebar loads different html templates using ng-include based on what operation the user chooses to do. It\'

相关标签:
3条回答
  • 2021-01-31 17:25

    I like this data driven scenario, just manipulate the rows in the templates:

    $scope.templates = [
        { name: 'include1.html', url: 'partials/include1.html' }
    ];
    $scope.addTemplate = function(name, url) {
        $scope.templates.push({ name: name, url: url });
    };
    

    and the markup:

    <div ng-repeat="template in templates" ng-include="template.url"></div>
    

    To add or remove views, just modify the templates et voila! If you need more controller code, then you can include a link to the script in the include. I guess there may be complications with binding to data in the partial view itself, but $compile should resolve those.

    0 讨论(0)
  • 2021-01-31 17:26

    I've forked your plunkr demo into one that I believe does what you're looking for: http://plnkr.co/edit/whsjBT?p=preview

    This demonstrates an event being broadcast from one controller to another AFTER the 2nd controller (LegCtrl in our example here) is loaded via ng-include and passing it data.

    I used $includeContentLoaded event from ng-include to delay broadcasting the event until angular reports that add_leg.html is loaded. Also I think there were some issues with how you were using $broadcast()... it's first parameter should be the same as the one used in $on() in LegCtrl

    Another idea to consider is simply using your Navigation service itself to share state between the controllers if that's appropriate in your scenario.

    0 讨论(0)
  • 2021-01-31 17:30

    If i have understood you correctly what you can try would be to create a template view specifically to create a new leg.

    From the main controller implement some logic to show the template

    $scope.addLeg=function() {
       $scope.showAddLeg=true;
    }
    

    The AddLeg template view would load the controller and hence provide a mechanism to actually add new leg. The template would look like

    <script type="text/ng-template" class="template" id="addLegTemplate">
        <div ng-controller='LegsController'>
        <!--html for adding a new leg-->
        </div>
    </script>
    

    You can include this template inside you main html using ng-if + ng-include.

    <div ng-if='showAddLeg'><div ng-include='addLegTemplate'/></div>
    

    Basically you can create multiple view and bind to same controller (but instance would differ). In this case the LegsController can be binded to multiple views to support the complete functionality.

    0 讨论(0)
提交回复
热议问题