Search code examples
javascriptangularjsangular-ui-router

change an angularjs nested template at run time


I have a template which is nested inside another template which I want to load when i click on a button. So the nested template is loaded dynamically. This is what I have done so far.

This is the main body.html (this loads when a url is provided in the browser e.g. http://url#/newtemplate)

<div ui-view> </div>

Other section of the code has been removed for brevity

This is the new_template.html which I expects it to show when I click a button.

When I put a template name directly like below i.e. when I hard code it

<div ui-view="number1"></div>

It loads the template fully.

This is the dynamic model

<button ng-model="template_name" ng-value="number1">Button1</button>
<div ui-view="{{template_name}}"></div>
{{template_name}}

The above does not load the template as I expected. but it shows the string number1 when the button is clicked

What can I do for it to load the template....

This is my controller

.state('parent',{
    url: '/newtemplate',
    views:{
        '':{
            templateUrl: "parent.tpl",
            contoller:"controller",
        },
         'number1@parent':{
            templateUrl:"number1.tpl",
            contoller:"formcontroller" 
        }, 
        'number2@parent':{
            templateUrl:"number2.tpl",
            contoller:"formcontroller"
        }, 
        'number3@parent':{
            templateUrl:"number3.tpl",
            contoller:"formcontroller"
        }
    }
})

Strange enough when I used the dot notation it did not work so I have to use the absolute naming method. I also noticed that when I added the nested views as shown above the time it takes before the template gets loaded take a very long time.

Please I would appreciate any help which can allow me to load a nested view at runtime (possibly very fast)

Expecting more answer

I still hope that the I can make use of ui-view/ui-router because of the ability to make use of controller.


Solution

  • I'm not sure you can use uiView to load html dynamically. I would try another possible solutions:

    • Use directives
    • Using ngInclude

    I'll leave you an example with ngInclude: https://next.plnkr.co/edit/M5hl71mXdAGth2TE?open=lib%2Fscript.js&deferRun=1&preview