Passing array via attribute to AngularJS directive

ArraysParsingAngularjsAttributesDirective

Arrays Problem Overview


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']" ... >

Arrays Solutions


Solution 1 - Arrays

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

https://stackoverflow.com/questions/14695792/binding-array-to-directive-variable-in-angularjs

Directive:

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

Template:

<post title="sample title" tags="arrayName" ... >

Solution 2 - Arrays

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
        }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHeberLZView Question on Stackoverflow
Solution 1 - ArraysAlex OsbornView Answer on Stackoverflow
Solution 2 - ArraysShahadat HossainView Answer on Stackoverflow