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.

Community
  • 1
  • 1
Jay Shukla
  • 5,794
  • 8
  • 33
  • 63

1 Answers1

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

        }
    }
}]);
Alborz
  • 6,843
  • 3
  • 22
  • 37
  • Thanks. Can you suggest me how to handle user interaction dynamically? Such like how to pass methods which can we call from dynamicComponent template. – Jay Shukla Jul 14 '14 at 13:09
  • You can simply add ng-click to your templates. the function could be declared in scope. – Alborz Jul 14 '14 at 13:18
  • 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 – Jay Shukla Jul 14 '14 at 13:39