angularjs将模板绑定为ngrepeat中的项目

时间:2014-03-16 06:56:19

标签: javascript angularjs angularjs-ng-repeat

我在angularjs中有一个特殊情况,我在ngRepeat内部无法模板,模板是项目的参数

<tr data-ng-repeat="item in items" >
<td data-ng-repeat="column in columns" ng-bind-html="resolve(item,column)"></td>
</tr>

控制器代码:

$scope.columns:[{ name: "id" },
            { name: "name" },
            { name: "lastName"},
            { name: "name", template: "<a href='#/xx/{{item.id}}' >edit</a>"},
            { name: "name", template: "<button ng-click='del()' href='#'>del</button>" }]

和解析功能是:

  $scope.resolve = function(item,col){
         if (col.template) {
            // i dont know for this
         } else {
          return sce.trustAsHtml("<span>" + item[col.name] + "</span>");
           }
    }                    

非常感谢任何帮助, 感谢

2 个答案:

答案 0 :(得分:0)

我对你的逻辑做了一些推测,但这对我来说就像指令的工作一样。

查看我为了表明我的观点而制作的那个:

http://plnkr.co/edit/zW6LYKNQxgfRszwY0eV2?p=preview

另请查看您提供的示例代码:

$scope.columns:[{ name: "id" },
            { name: "name" },
            { name: "lastName"},
            { name: "name", template: "<a href='#/xx/{{item.id}}' >edit</a>"},
            { name: "name", template: "<button ng-click='del()' href='#'>del</button>" }]

$ scope.columns = not:

答案 1 :(得分:0)

我已经完成了样本here之类的示例。在这个示例中,我创建了一个名为&#34; dynamic&#34;的自定义指令。在AngularJS中自动解析和编译HTML字符串。

HTML

<table ng-app="myApp" ng-controller="templateController">
    <tbody>
        <tr ng-repeat="item in items">
            <td ng-bind="item.name"><td>                               
            <td dynamic="item.template"></td>
        </tr>
    <tbody>
</table>

的Javascript

var myApp = angular.module('myApp', []);
myApp.directive('dynamic', function ($compile) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.dynamic, function(html) {
        ele.html(html);
        $compile(ele.contents())(scope);
      });
    }
  };
});
myApp.controller('templateController', function ($scope){
    $scope.items = [{ name: "id" },
            { name: "name" },
            { name: "lastName"},
                    { id: 1, name: "name", template: "<a href='#/xx/{{item.id}}' >edit</a>"},
            { name: "name", template: "<button ng-click='del()' href='#'>del</button>" }];
});

希望这会对你有所帮助!!