簡體   English   中英

Angular指令的鏈接函數不會操縱DOM

[英]Angular directive's link function won't manipulate DOM

我正在嘗試從服務訪問數據,以便可以使用jQuery處理ngRepeat ed列表。 我無法使link功能正常工作。 根據我所讀的內容,我希望無論哪種方式

app.directive('myDir', function() {
  return {
    restrict: 'E',
    templateUrl: 'url.html',
    link: function(scope, el, attrs) {
      //jQuery to manipulate DOM here
    }
  };
});

要么

app.directive('myDir', function() {
  return {
    restrict: 'E',
    templateUrl: 'url.html',
    compile: function(scope, el, attrs) {
      return {
        post: function() {
          //jQuery to manipulate DOM here
        }
      }
    }
  }
});

但是元素尚未在頁面上,因此它不起作用。 我想念什么?

嘗試等待一個$ digest階段。 這將為ng-repeat提供足夠的時間來呈現DOM元素。 您可以使用$ timeout。

link: function(scope, el, attrs) {
    $timeout(function() {
        //jQuery to manipulate DOM here
    });
}

編輯:

檢查以下示例。 在這里,我們有my-dir收集ng-repeat創建的所有元素。 有一個幫助程序mockup-box內部指令,該指令包括my-dir父指令控制器,並使用其方法注冊自身( 其元素 )。

然后, my-dir控制器調用invalidateChildren函數,該函數通過延遲validateChildren函數的執行來等待children指令的累積。

validateChildren函數中,我們操作DOM元素,並確保它們會在那里,因為每個元素僅在編譯時才注冊。 validateChildren函數中有一些偽代碼,但您可以在其中放置任何內容。

還有另外一個好處。 我們不再依賴ng-repeat,也不知道my-dir將如何創建子元素。 他們甚至可能是“靜態”孩子。 它還支持添加其他子代。 如果ng-repeat生成其他元素,它們將再次在父控制器中注冊並調用validateChildren函數。

 angular.module('example', []) .controller('AppCtrl', function($scope) { $scope.mockupData = ['a', 'b', 'c', 'd'] }) .directive('myDir', function() { return { controller: function($element, $timeout) { var ctrl = this; var childrenDirty = false; this.children = []; this.addChild = function(jqChild) { ctrl.children.push(jqChild); ctrl.invalidateChildren(); }; this.removeChild = function(jqChild) { var index = ctrl.children.indexOf(jqChild); if (index >= 0) { ctrl.children.splice(index, 1); } }; this.invalidateChildren = function() { if (!childrenDirty) { childrenDirty = true; $timeout(ctrl.validateChildren); } }; this.validateChildren = function() { childrenDirty = false; // Will be fire only once angular.forEach(ctrl.children, function(jqChild) { jqChild.html('value: "' + jqChild.html() + '"'); }); }; }, link: function() { } } }) .directive('mockupBox', function() { return { require: '^myDir', link: function(scope, iElement, iAttrs, myDirCtrl) { myDirCtrl.addChild(iElement); scope.$on('$destroy', function() { myDirCtrl.removeChild(iElement); }); } }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="example" ng-controller="AppCtrl"> <div my-dir> <div ng-repeat="data in mockupData" mockup-box>{{data}}</div> </div> </div> 

預期行為

  • mockupData值為['a','b','c','d'];
  • validateChildren函數編輯子元素的內容,並在前面添加“ value:”。

代碼執行的結果將是每個子元素的value: "<letter>"

暫無
暫無

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

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