Passing array via attribute to AngularJS directive
Asked Answered
N

2

55

I'm currently having a problem when passing an array to a directive via an attribute of that directive. I can read it as a String but i need it as an array so this is what i came up with but it doesn't work. Help anyone? thks in advance

Javascript::

app.directive('post', function($parse){
    return {
        restrict: "E",
        scope:{
            title: "@",
            author: "@",
            content: "@",
            cover: "@",
            date: "@"
        },
        templateUrl: 'components/postComponent.html',
        link: function(scope, element, attrs){
            scope.tags = $parse(attrs.tags)
        }
    }
}

HTML::

<post title="sample title" tags="['HTML5', 'AngularJS', 'Javascript']" ... >
Noeminoesis answered 30/4, 2013 at 1:23 Comment(0)
O
62

If you're accessing this array from your scope, i.e. loaded in a controller, you can just pass the name of the variable:

Binding array to directive variable in AngularJS

Directive:

scope:{
        title: "@",
        author: "@",
        content: "@",
        cover: "@",
        date: "@",
        tags: "="
    },

Template:

<post title="sample title" tags="arrayName" ... >
Oriente answered 30/4, 2013 at 2:26 Comment(2)
What if it is an inline array: tags="[1 ,2 ,3]" ? Edit: I found my answer here: https://mcmap.net/q/339455/-angularjs-pass-newly-created-array-in-attribute-to-directive/3328979Fogg
tags is undefined when i do console.log(scope.tags). what could be wrongSchaeffer
K
4

you can also have to use $scope instead of attrs. then you will get array object, otherwise you will get an string.

     scope:{
            title: "@",
            author: "@",
            content: "@",
            cover: "@",
            date: "@",
            tags: "="
        },


link: function(scope, element, attrs){
            scope.tags = scope.tags
        }
Karyoplasm answered 28/5, 2016 at 19:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.