简体   繁体   English

AngularJS指令控制器操纵DOM

[英]AngularJS directive controller manipulating the DOM

The Developer's Guide says, controller specified inside a directive is instantiated before the pre-link function and also that it is NOT safe to do DOM manipulation in the pre-link function. 开发人员指南说,在指令内指定的控制器在预链接函数之前被实例化,并且在预链接函数中进行DOM操作也是不安全的。

Then why is it that controller takes as its third parameter, $transclude, which does DOM manipulation as in the following example: 那么为什么控制器将第三个参数$ transclude作为DOM操作,如下例所示:

testapp.directive('buttonBar', function() {
    return {
        restrict: 'EA',
        template: '<div class="span4 well clearfix"><div class="primary-block pull-right"></div><div class="secondary-block"></div></div>',
        replace: true,
        transclude: true,
        scope: {},
        controller: ['$scope', '$element', '$transclude', function ($scope, $element, $transclude) {
            $transclude(function(clone) {
                var primaryBlock = $element.find('div.primary-block');
                var secondaryBlock = $element.find('div.secondary-block');
                var transcludedButtons = clone.filter(':button'); 
                angular.forEach(transcludedButtons, function(e) {
                    if (angular.element(e).hasClass('primary')) {
                        primaryBlock.append(e);
                    } else if (angular.element(e).hasClass('secondary')) {
                        secondaryBlock.append(e);
                    }
                });
            });
        }],
    };
});

in the discussion from http://blog.omkarpatil.com/2012/11/transclude-in-angularjs.html http://blog.omkarpatil.com/2012/11/transclude-in-angularjs.html的讨论中

Thanks 谢谢

It seems like the function that you pass to $transclude is executed during the link phase: https://github.com/angular/angular.js/blob/v1.1.5/src/ng/compile.js#L471 看起来传递给$ transclude的函数在链接阶段执行: https//github.com/angular/angular.js/blob/v1.1.5/src/ng/compile.js#L471

EDITED : I changed the GH reference to a tagged release so that there is no ambiguity about what code I'm referencing. 编辑 :我将GH引用更改为标记版本,以便对我引用的代码没有歧义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM