2017-08-28 58 views
0

我做了一个指令来调用博客门户的相关帖子。它应该通过传递阅读帖子的标签,像一个名为“标签”的属性。但是,当我尝试这样做时,该指令返回文字内容而不是变量值。在AngularJS中传递属性的数据

<!-- Here works fine --> 
<related-posts labels="post.labels"> {{ labels }} </related-posts> 

// Here my issue 
app.directive('relatedPosts', function ($http) { 
    return { 
     restrict: 'E', 
     templateUrl: 'app/components/templates/related-posts.html', 
     scope: { 
      labels: '=' 
     }, 
     controller: function($scope, $element, $attrs) { 
      console.log($attrs['labels']); // returns "post.labels" instead "Label 1, Label 2, etc..." 
     } 
    } 
}); 

回答

2

请访问像这样的变量。

说明:您已经安装范围正确,但使用的是$attrs.labels这将只是获得标签值作为文本,因此你post.labels,因为你绑定了范围,你需要访问它像$scope.labels

JSFiddle

<!-- Here works fine --> 
<related-posts labels="post.labels"> {{ labels }} </related-posts> 

// Here my issue 
app.directive('relatedPosts', function ($http) { 
    return { 
     restrict: 'E', 
     templateUrl: 'app/components/templates/related-posts.html', 
     scope: { 
      labels: '=' 
     }, 
     controller: function($scope, $element, $attrs) { 
      console.log($scope.labels); 
     } 
    } 
}); 
相关问题