0

I'm trying to create a custom directive and send an array into it to create a dynamic template. I've looked at these two questions:

Binding array to directive variable in AngularJS

Passing array via attribute to AngularJS directive

I'm using the same code basically but when I console log the tAttrs it only shows tags as "testArray" instead of Array(2) as it would be should the tags="testArray" be interpreted correctly.

From what I can see I haven't done anything wrong here so it's kinda driving me to insanity why it's not working.

Can someone point out why this isn't working as expected?

The controller containing the array:

forumApp.controller('profileCtrl', ['$scope', function($scope) {
    $scope.testArray = ['displayName', 'email'];
}

The directive markup:

<error tags="testArray"></error>

And the directive:

forumApp.directive('error', [function() {

    return {
        restrict: 'E',
        scope: {
            tags: "="
        },
        template: function(tElement, tAttrs) {
            console.log(tAttrs);
            return "<div ng-if='row.model === " + tAttrs.tags[0] + "'>Hello world</div>";
        }
    }
}]);
Community
  • 1
  • 1
Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
  • There are problems with your directive. First: attributes are not the right way to get scope values. Second: you are creating isolate scope and you are probably using values from the parent scope(row). – Ufuk Hacıoğulları Mar 05 '15 at 12:12
  • @UfukHacıoğulları Give me suggestion on how to change it then, and from the questions I included it appears that it's indeed the way to do it? Makes me a bit confused. – Chrillewoodz Mar 05 '15 at 12:15
  • You can move the ng-if outside the directive: ``. Then you wouldn't need to create an isolate scope in your directive. – Ufuk Hacıoğulları Mar 05 '15 at 12:21
  • @UfukHacıoğulları Not sure if that would work with the complete example, because I've got additional elements within the div that also uses if-statements. – Chrillewoodz Mar 05 '15 at 12:24
  • You can't access parent scope elements in an isolated scope. Are you aware of that? `row` is not defined in the directive scope. – Ufuk Hacıoğulları Mar 05 '15 at 12:27

1 Answers1

0

If you are going to put the array in isolated scope, you don't need tAttrs anymore:

template: function(tElement) {
            return "<div ng-if='row.model === " + tags[0] + "'>Hello world</div>";
        }

The above template will look for tags on the isolated scope. tAttrs was pulling the raw attribute off of the element.

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132