在ng-repeat指令中访问DOM

时间:2016-04-06 18:13:33

标签: javascript angularjs dom ng-repeat

您好我是AngularJS的新手,并已开始学习如何构建指令

在我的示例中,我试图访问在我的指令中呈现的DOM元素,但我无法访问某些元素,因为它们尚未在我的链接函数中呈现。

如何使用ng-repeat和指令访问这些元素?

在我的示例中,我可以获取“p”并更改其颜色,但我无法访问td以更改其css属性,绑定事件等

HTML

<div ng-app="app">
    <div ng-controller="myController as myCtrl">        
        <my-table list="myCtrl.list"></my-table>
    </div>
</div>

JS

// Main module
(function() {
    var app = angular.module("app", []);
}());

// Controller
(function() {
    angular.module("app")
        .controller("myController", myController);

    function myController() {
        var vm = this;
        vm.list = [
            { id: 1, name: "Alan" },
            { id: 2, name: "Jasmine" }
        ];
    }
}());

// Directive
(function() {
    angular.module("app")
        .directive("myTable", myTable);

    function myTable() {
        var directive = {
            link: link,
            replace: true,
            restrict: "E",
            scope: {
                list: "="
            },
            template: "<div>" +
                          "<p>My Table</p>" +
                          "<table>" +
                              "<tr ng-repeat='item in list'>" +
                                 "<td>{{item.id}}</td>" +
                                 "<td>{{item.name}}</td>" +
                              "</tr>" +
                          "</table>" +
                      "</div>"
        };

        function link(scope, element, attrs) {
            // "p" element is accesible and we can change the color
            var p = element[0].querySelector("p");
            angular.element(p).css("color",  "red");

            // CANNOT FIND TR'S, the element tag contains <!-- ngRepeat: item in list -->
            var trs = element[0].querySelector("tr");
            // ????????????????
        }

        return directive;
    }
}());

https://jsfiddle.net/hkhvq1hn/

我擅长任何帮助或建议 最好

1 个答案:

答案 0 :(得分:0)

在呈现它之后,你不能将它包装在$ timeout内以访问DOM吗?

function link(scope, element, attrs) {
            // "p" element is accesible and we can change the color
            var p = element[0].querySelector("p");
            angular.element(p).css("color",  "red");

            // Wrap selector inside $timeout to access DOM after rendering it -->
            $timeout(function(){
                var trs = element[0].querySelector("tr");
                console.log(trs); 
            });

    }

检查更新的fiddle