将数组via属性传递给AngularJS指令

时间:2013-04-30 01:23:39

标签: arrays parsing angularjs attributes directive

当通过该指令的属性将数组传递给指令时,我当前遇到了问题。我可以把它读作一个字符串,但我需要它作为一个数组,所以这是我想出来但它不起作用。帮助任何人?提前知道

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

2 个答案:

答案 0 :(得分:59)

如果您从示波器访问此数组,即在控制器中加载,您只需传递变量的名称:

Binding array to directive variable in AngularJS

<强>指令:

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

<强>模板:

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

答案 1 :(得分:4)

您还必须使用$ scope而不是attrs。然后你会得到数组对象,否则你会得到一个字符串。

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


link: function(scope, element, attrs){
            scope.tags = scope.tags
        }