0

I have a small amount of js in the app.js file that I needed in order to manipulate the DOM in this Angular Grid: http://plnkr.co/PXRgUA You can see it in app.js.

$('.userRow ').live('click', function(e) {
    $(this).find('span.userDetailRow.blueRow').show().animate({height:200},500);

});

$('.closeDetails').live('click', function(e) {
    $(this).parent('span').animate({height:0}, 500).animate({height:0},500).hide();
    e.stopPropagation();
});

How can I move this to a directive? Does it have to be moved to a directive? It does not seem right here.

4

1 回答 1

1

是的,您可以(并且应该)将其移至指令中。为了清楚起见,我将在此处包含您的旧代码:

   $('.userRow ').live('click', function(e) {
    $(this).find('span.userDetailRow.blueRow').show().animate({height:200},500);

});

$('.closeDetails').live('click', function(e) {
    $(this).parent('span').animate({height:0}, 500).animate({height:0},500).hide();
    e.stopPropagation();
});

这(使用 jquery 绑定事件侦听器)是人们口口声声描述为“不是角度方式”的方式。相反,您可以使用 ng-click(它只是一个内置指令)来调用 javascript 函数:

<tr row ng-click="expandRow()" ng-repeat="user in users" class="item-in-list el userRow" animate="fadeIn">

<span class="userDetailRow blueRow" style="display:none;"><span close ng-click="closeDetails(); $event.stopPropagation()">x</span>

您可以在此处看到在这些元素上定义了两个自定义属性。这些链接到下面的指令。这些指令在其链接函数中定义了自定义函数,然后您可以使用 ng-click 调用这些函数(但请注意,这会将这些函数置于全局范围内)。

.directive('close', function() {
      return {
        restrict: 'A',
        replace: false,
        link: function($scope, element, attrs) {

            $scope.closeDetails = function() {
              $(element).parent('span').animate({height:0}, 500).animate({height:0},500).hide();
            }
        }
    }
})

.directive('row', function() {
  return {
    restrict: 'A',
    replace: false,
    link: function($scope, element, attrs) {
      $scope.expandRow = function() {
        $(element).find('span.userDetailRow.blueRow').show().animate({height:200},500);
      }

    }
  }
});

为了简单起见,这里仍然使用 jQuery 来定位和修改元素,因此您可以看到您的旧逻辑去了哪里。但是,理想情况下,您应该将其更改为使用 Angular 的内置动画功能。(有关动画在新 Angular 版本中如何工作的更多信息:http ://www.yearofmoo.com/2013/08/remastered-animation-in-angularjs-1-2.html )

Plunker在这里:

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

于 2013-10-04T08:58:02.930 回答