suman j
suman j

Reputation: 6960

How to access the attribute of angular directive in templateUrl html content

How do I access the attribute of angular directive in templateUrl html content?

angular.module('myApp')
    .directive('questionImage', function () {
        return {
            restrict : 'E',
            scope : false,
            templateUrl : 'templates/questionImage.html',
            link : function(scope, element, attrs) {
                scope.type = attrs['type'];
            }
        }
    });

template HTML:

<div>
    <label>Image Links</label><br>
    <button type="button" ng-click="newImageLink('{{type}}')">+</button>
    <span ng-repeat="imageLink in questionFormData.imageUrls['{{type}}'] track by $index">
        <input type="text" ng-model="questionFormData.imageUrls['{{type}}'][$index]">
        <button type="button" ng-click="removeElement(questionFormData.imageUrls['{{type}}'], $index)">-</button>
    </span>
</div>

Inside this HTML, I need to access the "type" attribute value specified when the directive is used in DOM such as below.

<question-image type="optionAImages"></question-image>
<question-image type="optionBImages"></question-image>  

How do I get "type" attribute value inside the template html?

Update: Added the 'link' function in the directive definition. I was able to get the type but its value is always the last directive usage. i.e I always see optionBImages value for type attribute. optionAImages value is not available.

Upvotes: 0

Views: 877

Answers (2)

Mostafa Ahmed
Mostafa Ahmed

Reputation: 661

the problem comes from the scope:false statement as as the second call of the question-image directive override the parameter changed by the first call of the same parameter

you need to change the scope:false to be scope:true

this will not create an isolated scope but it will give the directive a nested scope of the parent scope of the controller.

Upvotes: 2

byrdr
byrdr

Reputation: 5487

 return {
           restrict : 'E',
           scope : {
           type : '@'
        },
           templateUrl : 'templates/questionImage.html'

This is equivalent to

scope.type = attrs.type; 

Upvotes: 1

Related Questions