2

I'm using AngularJS in my project !

I have following JSON

{
    "headers" :["A","B","C"]
    "rows":[
        ["a","b","c"],
        ["d","e","f"]
    ]
}

Also following template:

<table>
    <thead>
        <tr>
            <th ng-repeat="header in data.headers" ng-bind="header"></th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="row in data.rows">
            <td ng-repeat="item in row track by $index" ng-bind="item"></td>
        </tr>
    </tbody>
</table>

I want to change

<td ng-repeat="item in row track by $index" ng-bind="item"></td>

to

<td ng-repeat="item in row track by $index" ng-bind="item" data-my-directive></td>

and get this:

<td data-title='C'>f</td> // `C` refer to headers[2], because f is row[2]

The main qusetion is, how to define a directive and force that replace (not add) the attribute, not whole HTML tag. (not how to access headers[2] value or something like that)

As we know, the template (or templateUrl) of a directive define a complete HTML tag structure (for example <div>SOMETHING</div>) and replace that (if replace: true) or append the template inside the caller tag.

Please note

Now I have no error or issue, everything working fine, but I need this solution to add more future to my code. I mean I got JSON data on the table and no problem with this part.

1 Answer 1

1

There is no out of the box solution that works like replace:true but affect attribute instead of tag.

If you really need this, you can remove the attribute in the link function

angular
  .module('app')
  .directive('myDirective', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attributes) {
            element.attr('data-title', 'C');
            element.removeAttr('myDirective');
        }
    };
});
Sign up to request clarification or add additional context in comments.

5 Comments

this answer "how to define a directive and force that replace one attribute, not whole HTML tag" for me
your solution add new data-x to the tag, but the question is "ow to define a directive and force that replace (not add) the attribute, not whole HTML tag"
Do you mean, you want to remove data-my-directive, ng-bind attributes and replace it with your data-title attribute ?
not ng-bind, just replacing name of directive with new data-x attribute

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.