55

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

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

2 回答 2

62

如果您正在从您的范围访问此数组,即加载到控制器中,您可以只传递变量的名称:

将数组绑定到AngularJS中的指令变量

指示:

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

模板:

<post title="sample title" tags="arrayName" ... >
于 2013-04-30T02:26:56.047 回答
4

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

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


link: function(scope, element, attrs){
            scope.tags = scope.tags
        }
于 2016-05-28T19:50:52.433 回答