簡體   English   中英

如何使用Angular在JQueryUI手風琴中填充數據?

[英]How to populate data in JQueryUI accordion using Angular?

在下面的代碼示例中, 手風琴指令確保首先完成角度,然后允許JQueryUI用標簽中提供的值呈現手風琴。 但是它沒有按預期工作。 我正在跟蹤此鏈接

<div accordion>
  <h3 ng-repeat-start="user in users" >
    <a href="#">{{user.name}}</a>
  </h3>
  <div ng-repeat-end>
      Name: {{user.name}}<br>
      Type: {{user.type}}<br>
  </div>
</div>


以下是手風琴指令的實現`

app.directive('accordion', function ($timeout) {
  return {
    restrict: 'A',
      link: function ($scope, $element, attrs) {
        $(document).ready(function () {
          $scope.$watch('users', function () {
            if ($scope.users != null) {
              $timeout(function(){
                $element.accordion();
              });
            }
          });
        });
      }
  };
});

JS小提琴https://jsfiddle.net/7028yLdh/1/

除非Array更改為其他對象,否則不會調用$scope.$watch('users', /* ... */) 因此,在編譯DOM之后,您的elem.accordion()不會運行。 相反,您可以觀看users.length來檢測數組中的新元素。

另外,Angular指令鏈接函數中不需要$(document).ready

另一個陷阱是,您必須調用elem.accordion('destroy')並在隨后對數組進行的更改上重新構建手風琴。 我的解決方案默認情況下只會構建一次手風琴,除非您提供watch="someVariable"來監視更改。

小提琴: https : //jsfiddle.net/hk6wro4y/

HTML:

<!-- Will not update -->
<div accordion><!-- content --></div>

<!-- Will update -->
<div accordion watch="users.length"><!-- content --></div>

JS:

app.directive('accordion', function ($timeout) {
    return {
        link: function (scope, elem, attrs) {          
          if (attrs.watch) {
            scope.$watch(attrs.watch, function () {
              if (elem.hasClass('ui-accordion')) { 
                elem.accordion('destroy'); 
              }
              elem.accordion();
            });
          }
          else {
            $timeout(function () {
              elem.accordion();
            });
          }
        }
    };
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM