AngularJS - Render multiple strings and HTML files

2019-09-07 20:48发布

问题:

I want to render template files (view + controller) and multiple html strings both together in a single tag. - So I have some strings like

<p>some text</p>

and html files + controller like

template.html + template.controller.js

I want to render the strings and the template.html into one tag.

I already connected the html strings and I'm able to render these with

<div ng-bind-html="template" ..></div>

Can I serialize the html files and render it in ng-bind-html too? These files have own controllers:

<div ng-controller="sampleCtrl">

They would lose functionality?

NOTE: The order of the elements is important!!! For example, I want to render the string, then the content of the file and then again a string.

Thanks a lot!

回答1:

You should use directives. This will allow you to load a html file with an associated js file. You can set scope.someText in the directive and call it in the view e.g.

 <p>{{someText}}</p>

Directive:

var app = angular.module('myApp');

app.directive('someTextDirective', function(){
    return{
         restrict: 'E',
         templateUrl: 'path/to/html/file.html',
         link:function(scope){
              scope.someText = 'blah';
         }
    }
});

Simply call the directive in your html:

<some-text-directive></some-text-directive>

Hope this helps. If I have not been clear let me know and I will do my best to clarify.