2015-01-08 83 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并在它们之间切换。