1
votes

I want help to get value in templateUrl. I already go through similar question like this Set templateUrl base on attribute in directive

My Goal

I want to set one attribute while calling directive from HTML. This attribute will have dynamic value from the json object. And I want this attribute in directive's templateUrl function.

You can see here to understand my issue more - jsfiddle

I want to render checkbox or radio template based on attribute value.

Please help.

I know ng-include approach so please suggestion alternate solution.

1

1 Answers

2
votes

scope is not accessible in tempalteUrl function. In link function you can access the template Url as well as the scope. I changed your code here.

angular.module("myApp",[]).controller("myCtrl",['$scope',function($scope) {
    $scope.dynamicAttr = [
        {
            style:"stdRadio",
            label:"First Box"
        },
        {
            style:"stdCheck",
            label:"Second Box"
        }
    ];
}]).directive("dynamicComponent",['$compile','$http','$templateCache',function($compile, $http,$templateCache) {
    return {
        scope:{
            sourceData:"=sourceData"
        },
        restrict:"E",

        link: function (scope, element, attrs) {
            $http.get((scope.sourceData.style == "stdRadio")?"dynamicComponentRadio.html":"dynamicComponentCheckBox.html", {cache: $templateCache}).then(function(data){

         element.html(data.data);
         return $compile(element.contents())(scope);
            });

        }
    }
}]);