Angular.js directive with dynamic templateURL

2
create.directive('renderInputs', [ function(){
    return {
        restrict: 'E',
        scope: true,
        templateUrl: function(elem, attrs) {
            alert(attrs.type);
            return '../templates/inputs/type-' + attrs.type + '.html';
        }
    }
}]);

<render-inputs  type="{{ p.input.type }}"></render-inputs>
  • Error: Error: [$compile:tpload] Failed to load template: ../templates/inputs/type-{{ p.input.type }}.html (HTTP status: 404 Not Found)

I'm having trouble loading a template dynamically. My alert is returning {{ p.input.type }} , in fact it was to return a type with these values: radio, checkbox, etc. for example: '../templates/inputs/type-radio.html'

    
asked by anonymous 19.04.2017 / 19:41

1 answer

1

This is happening because the value is being passed literally, without evaluation in the context of scope.

In theory you can use $scope.eval(attrs.type) to evaluate the expression: however this is not a very elegant solution.

Use a template with ng-include , at the same time it forces the evaluation of the expression {{ p.input.type }} via the @ scope marker. Functional example below:

var create = angular.module("create", []);

create.controller("testController", function ($scope) {});

create.directive('renderInputs', function() {
       return {
           restrict: 'E',
           scope: { type: "@type" },
           link: function(scope, element, attrs) {
           
               scope.contentUrl= function() {
                    return 'type-' + scope.type + '.html';
               }
           },
           template: '<div ng-include="contentUrl()"></div>'
       }
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script><linkrel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script type="text/ng-template" id="type-radio.html">
    <input type='radio' />
</script>

<script type="text/ng-template" id="type-text.html">
    <input type='text' />
</script>

<body ng-app='create'>
    <div ng-controller="testController">
         <render-inputs type='radio'></render-inputs>
         <render-inputs type='text'></render-inputs>
    </div>
</body>

This response is a adaptation of this post in the original OS.

    
20.04.2017 / 00:40