0

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.

2
  • Sounds Like you need ISOLATED SCOPE Commented Dec 28, 2014 at 4:59
  • @underscore I can not isolate the scope as I need lot of functionality from the parent controller. Also See my update Commented Dec 28, 2014 at 5:08

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

This is equivalent to

scope.type = attrs.type; 

Comments

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.