简体   繁体   中英

Use variable as expression in ng-include

This code works:

<div ng-include src="'Test.html'"></div>

This code doesn't:

<div ng-include src="ctrl.URL"></div>

( ctrl.URL is set to "Test.html" ). I also set it to 'Test.html' and "'Test.html'" with the same results.

How can I successfully convert this into an expression for use in ng-include src? I think I am missing some knowledge on how strings get parsed but I was pretty sure 'Test.html' should work.

I found that I am too incompetent to rename my own variables. ctrl.URL was really ctrl.URl. Now everything is working.

Check this, maybe this fiddle will help you.

HTML and templates:

 <div ng-controller="Ctrl">
    <select ng-model="template" ng-options="t.name for t in templates">
     <option value="">(blank)</option>
    </select>
    url of the template: <tt>{{template.url}}</tt>
    <hr/>
    <div ng-include src="template.url" onload='myFunction()'></div>
  </div>

<!-- template1.html -->
<script type="text/ng-template" id="template1.html">
  Content of template1.html
</script>

<!-- template2.html -->
<script type="text/ng-template" id="template2.html">
    <p ng-class="color">Content of template2.html</p>
</script>

The controller:

function Ctrl($scope) {
    $scope.templates = [{
        name: 'template1.html',
        url: 'template1.html'},
    {
        name: 'template2.html',
        url: 'template2.html'}];
    $scope.template = $scope.templates[0];

    $scope.myFunction = function() {
        $scope.color = 'red';
    }
}

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