angularjs对指令和模型的混淆

时间:2013-06-06 22:47:30

标签: javascript angularjs angularjs-directive

我这样做了吗?我的范围从控制器分配了一些json。我正在使用angularForEach迭代它。

我希望能够将我的td数据格式化为日期。这是一个微不足道的例子。理想情况下,我想在行值上使用日期过滤器,但语法似乎不正确。 [编辑]我想我需要使用“插值”[/ EDIT]

大多数示例都使用大括号,似乎在实际视图中。有人可以提出建议 - 我很害怕我会走自己的路。

.directive('betterTable', function () {
    return {
        restrict: 'E',        
        link: function ($scope, element, attrs) {

            var html = '<table border="1" width="100%">';
            html += '<tr>';
            angular.forEach($scope.result, function (row, index) {
                html += '<td>'; 
                html += row;
                html += '</td>';
            });
            html += '</tr></table>';

        }
   } 
 });

2 个答案:

答案 0 :(得分:1)

你可以这样做:

.directive('betterTable', function () {
  return {
    restrict: 'E',
    template: '<table border="1" width="100%">' +
      '<tr>' +
        '<td ng-repeat="row in result">{{row|date:"short"}}</td>' +
      '</tr>' +
    '</table>',
    link: function ($scope, element, attrs) {
      // Nothing to see here...
    }
  } 
});

老实说,你真的不需要这个指令。

如果你真的想在链接功能中做循环(我不建议),这应该让你开始:

.directive('betterTable', ['$compile', function ($compile) {
  return {
    restrict: 'E',        
    link: function ($scope, element, attrs) {

        var html = '<table border="1" width="100%">';
        html += '<tr>';
        angular.forEach($scope.result, function (row, index) {
          html += '<td>';
          html += $compile("{{row|date:'short'}}")($scope);
          html += '</td>';
          // This could also be expressed on one line as:
          // html += $compile("<td>{{row|date:'short'}}</td>")($scope);
        });
        html += '</tr></table>';

    }
  } 
}]);

编辑:为了清楚起见,根据您发布的内容,我认为没有任何理由来创建指令。你可以把它放在你看来:

<table border="1" width="100%">
  <tr>
    <td ng-repeat="row in result">{{row|date:"short"}}</td>
  </tr>
</table>

答案 1 :(得分:0)

如果您仍想创建指令,那么设置部分HTML文件呢?

指令

.directive('betterTable', ['$compile', function () {
  return {
    restrict: 'E',
    templateURL: '/root/to/partials/better_table.html',
    link: function ($scope, element, attrs) {
        // As you're not restricting the scope, $scope.result will exist here.
    }
  } 
}]);

better_table.html(正如@rtcherry提议的那样)

<table border="1" width="100%">
  <tr>
    <td ng-repeat="row in result">{{row|date:"short"}}</td>
  </tr>
</table>

这样,您将获得更好的结构化代码以及适当更新的范围:)

希望有所帮助