简体   繁体   中英

AngularJS: Dynamically loading HTML with a controller

I'm new to AngularJS and I'm working on a small project to get the hang of how things work.

Basically I want to have a single-page app where I can dynamically change part of the page to include html from some other file. This other file has a controller and such. I would like the url to stay the same. I need the page to be loaded dynamically with a variable name.

Right now, I can get the HTML to load from the imported template, but a lot of HTML is excluded and all of the "ng" tags are gone. I take this to mean that this new page can't find the controller or a lot of the stuff is getting compiled out or something. Maybe I'm not importing things in the correct order? I have no idea. Here's my basic layout:

app.js

var app = angular.module('myApp', []);
app.controller('Main', function($scope) {
    $scope.htmlContent = 'somepage.html';
    $scope.externalPage = 'otherpage';
    $scope.changePage = function(page) {
        $scope[page]();
    }
    $scope.otherpage = function() {
        $scope.htmlContent = 'otherpage.html';
    }
});

app.controller('InternalPage', function($scope) {
    alert('hello world');
    $scope.content = "This is not showing";
});

index.html

<div ng-controller="Main">
    <!-- This all works.  Clicking "Change Page" changes the 
         HTML referenced by the <div> tag -->

    <a ng-click="changePage(externalPage)">Change Page</a>
    <div ng-bind-html="htmlContent"></div>
</div>

otherpage.html

<div ng-controller="InternalPage">
    <p>{{content}}</p>
</div>

I have tried including the javascript in the html file itself to no avail. I also could not get the ng-include thing to work either.

尝试查看ng-include而不是ng-bind-html: https : //www.w3schools.com/angular/angular_includes.asp

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