1

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 Answer 1

2

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);
            });

        }
    }
}]);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Can you suggest me how to handle user interaction dynamically? Such like how to pass methods which can we call from dynamicComponent template.
You can simply add ng-click to your templates. the function could be declared in scope.
Ya that I know but what my issue is how to call two different methods on two separate checkbox. Though that both checkbox will be render from one template only so how can I pass that methods and where should I define that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.