2015-01-08 136 views
0

我成立了一個以下面的方式稱爲ogPostList指令:傳遞屬性值到angularjs NG重複

angular.module('myApp') 
    .directive('ogPostList', function() { 
    return { 
     restrict: 'E', 
     scope: { 
     page: '@' 
     }, 
     templateUrl: '../scripts/directives/postList.html' 
    }; 
}); 

TemplateUrl:

<input type="text" ng-model="searchText" placeholder="Search" class="postListSearch" /> 
<table id="post_list_table" ng-controller="PostListController">   
    <tbody> 
     <tr ng-repeat="postItem in {{page}} | orderBy:'toString()' | orderBy:'date':true | filter:searchText"> 
      <td><img title="{{'Post source ' + postItem.source}}" src="{{'images/' + postItem.source + '.svg'}}" height="20"/></td> 
      <td>{{postItem.post}}</td> 
      <td width="70">{{postItem.date}}</td> 
     </tr> 
    </tbody> 
</table> 

控制器設置如下:

angular.module('myApp') 
    .controller('PostListController', function($scope, $http) { 

     var postsList = []; 
     var postsListSummary = []; 
     var postsListMain = []; 

     $http.get('dummy_content.json') 
      .then(function(res){ 
      postsList = res.data; 

      for (var iSummary = 0; iSummary < 10;iSummary++) { 
       postsListSummary[iSummary] = postsList[iSummary]; 
      } 

      for (var iMain = 0; iMain < postsList.length;iMain++) { 
      postsListMain[iMain] = postsList[iMain]; 
      } 

     }); 

     $scope.postsSummary = postsListSummary; 
     $scope.postsMain = postsListMain; 

    }); 

我想要做的是當我聲明一個og-post-list元素是通過我的頁面屬性傳遞一個值。

<og-post-list page="postsSummary"></og-post-list> 

此值{{PAGE}}然後應該去NG重複節中我templateURL再拉合適的陣列,如圖在我的控制器,以填充我的表

<tr ng-repeat="postItem in {{page}} | orderBy:'toString()' | orderBy:'date':true | filter:searchText"> 

但是我看到這是不允許的?爲什麼會這樣,以及什麼是更好的方法來告訴我的指令顯示兩個數組中的一個。 2個數組之間的唯一區別是1個數組只包含10個項目,而數組2包含從我的json文件中提取的所有元素

+0

這項工作適合您嗎? – tasseKATT

+0

剛剛試過你的解決方案,它的作品非常漂亮:) – ocajian

+0

好聽:) – tasseKATT

回答

1

在執行編譯函數ng-repeat之前,可以使用編譯函數修改模板。

例如:

app.directive('ogPostList', function() { 
    return { 
    restrict: 'E', 
    templateUrl: 'postList.html', 
    compile: function compile(tElement, tAttrs) { 

     tElement.html(tElement.html().replace('{{page}}', tAttrs.page)); 

     return { 
     pre: function preLink(scope, iElement, iAttrs) {}, 
     post: function postLink(scope, iElement, iAttrs) {} 
     }; 
    }, 
    }; 
}); 

演示:http://plnkr.co/edit/whwwHTZfMvlABlfkhjKK?p=preview

一種替代的解決方案是具有第三可變的,例如postsDisplay和使用,在所述ng-repeat。然後,您可以將postsDisplay設置爲postsSummarypostsMain並在它們之間切換。