2017-08-28 61 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); 
     } 
    } 
}); 
相關問題