【问题标题】:Passing array via attribute to AngularJS directive通过属性将数组传递给 AngularJS 指令
【发布时间】:2013-04-23 20:03:16
【问题描述】:

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

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 parsing angularjs attributes directive


    【解决方案1】:

    如果你从你的作用域访问这个数组,即加载到控制器中,你可以只传递变量的名称:

    Binding array to directive variable in AngularJS

    指令:

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

    模板:

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

    【讨论】:

    • 如果是内联数组怎么办:tags="[1 ,2 ,3]"?编辑:我在这里找到了答案:stackoverflow.com/q/20811527/3328979
    • 当我 console.log(scope.tags) 时,标签未定义。可能出了什么问题
    【解决方案2】:

    您也可以使用 $scope 代替 attrs。然后你会得到数组对象,否则你会得到一个字符串。

         scope:{
                title: "@",
                author: "@",
                content: "@",
                cover: "@",
                date: "@",
                tags: "="
            },
    
    
    link: function(scope, element, attrs){
                scope.tags = scope.tags
            }
    

    【讨论】:

      猜你喜欢
      • 2016-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-18
      • 2016-05-10
      • 1970-01-01
      • 2016-04-27
      • 1970-01-01
      相关资源
      最近更新 更多