2

我是 AngularJS 的新手。我想用来ng-repeat呈现数据列表。

每个数据<abbr class="timeago" title="2012-10-10 05:47:21"></abbr>在渲染后都应该有一个相似的。然后我可以使用 jquery 插件timeago把它变成人类友好的文本about 1 hour ago

我的代码如下。但它没有任何效果。请帮忙。

编辑:我的问题是,我可以得到正确的 html 呈现。但是代码在directive不运行。

的HTML:

<div ng-app='weiboApp' ng-controller="WeiboListCtrl">
<table><tbody>
<tr ng-repeat='w in weibo' weiboLister='w'>
  <td>{{ w.text }}></td>
  <td><abbr class="timeago" title="{{ w.created }}"></abbr></td>
</tr>
</tbody></table>
</div>

js:

var module = angular
            .module('weiboApp', [])
            .directive('weiboLister', function () {
              return {
                restrict: 'A',
                link: function (scope, element, attr) {
                  scope.watch('w', function (val) {
                    console.log(element); //this never run
                    element.find("abbr.timeago").timeago(); //this never run
                  }, true);
                }
              }
            });

function WeiboListCtrl($scope, $http) {
  $http.get('/api/weibo/list').success(function(data) {
    $scope.weibo = data;
  });
}
4

1 回答 1

1

问题原来是:应该用 camel-case 定义指令weiboLister并在 html 中使用它和 snake-case weibo-lister感谢@tosh shimayama。

正确的代码如下:(我添加了一个remove功能,以防您正在寻找相同的东西。)

的HTML:

<div ng-app='weiboApp' ng-controller="WeiboListCtrl">
<table><tbody>
<tr ng-repeat='w in weibo' weibo-lister='w'> <!--important to be snake-case here-->
  <td>{{ w.text }}></td>
  <td><abbr class="timeago" title="{{ w.created }}"></abbr></td>
  <td><a ng-click='remove(w)'>&times;</a></td>
</tr>
</tbody></table>
</div>

js:

var module = angular
        .module('weiboApp', [])
        .directive('weiboLister', function () {
          function delete(id, s_function, f_function) {
            //...
            if success { s_function(); }
            else { f_function(); }
          }
          return {
            restrict: 'A',
            link: function (scope, element, attr) {
              scope.$watch('w', function (val) {
                element.find("abbr.timeago").timeago();
              }
              scope.destroy = function(callback) {
                deletenews(scope.w.id, function () {
                  //s_function, things you want to do when delete with success
                  element.fadeOut(400, function () {
                    //this callback will splice the element in model
                    if (callback) callback.apply(scope);
                  })
                }, function () {
                  //f_function, when delete with failure
                });
              };
            }
          }
        });

function WeiboListCtrl($scope, $http) {
  $http.get('/api/weibo/list').success(function(data) {
    $scope.weibo = data;
  });

  $scope.removeWeibo = function(w) {
    var idx = $scope.weibo.indexOf(w);
    if (idx !== -1) {
      this.destroy(function() {
        $scope.weibo.splice(idx, 1);
      });
    }
  };
}
于 2012-10-10T07:57:25.380 回答