Load AngularJS Template within page, dynamically

老子叫甜甜 提交于 2019-12-18 10:24:40

问题


I have a page containing 2 controllers: one which manages a list of so-called 'apps', and another that is to place the new Angular template into the innerHTML of its Div element.

<div ng-controller="appList"></div>
<div ng-controller="appPane"> Dynamic content should be loaded here! </div>

I have tried using the standard {{expression}} bindings, but they do not work with html, I have also tried the ng-bind-html-unsafe directive (Binding the innerhtml to that of the App request's return) but controllers are not executed within this new code.

The problem seems to be that by using a Binding, Angular is not re-parsing the contents of the html in question to use it as an angular app. Any ideas of how to get it to parse dynamic content?


回答1:


Take a look at the uiRouter module (from the AngularUI project). It adds the concept of states, which are pretty similar to routes, but with other goodies, such as the ability to nest them. For example:

$stateProvider
    .state('myState', {
        url: '/mystate',
        templateUrl: '...',
        controller: 'MyCtrl'
    })
    .state('myState.substate', {
        url: '/{substate}',
        templateUrl: '...',
        controller: 'MySubCtrl'
    });

MySubCtrl will be activated whenever you go to /mystate/something and you can use that "something" as a parameter (see $stateParams). You can nest states to any amount of levels.




回答2:


It appears that the $compile service, when fed the elements you wish to recompile along with your current scope, does what I was looking for.

Example from my source:

var appPane = $('#AppPane');//JQuery request for the app pane element.
appPane.html(data);//The dynamically loaded data
$compile(appPane.contents())($scope);//Tells Angular to recompile the contents of the app pane.

This should help anyone experiencing my problem, I hope.




回答3:


Look at $routes and ngView in angularjs.

Here's a very basic example:

http://jsfiddle.net/pXpja/3/



来源:https://stackoverflow.com/questions/11318337/load-angularjs-template-within-page-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!