Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/433.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 访问尚未编译的指令';从控制器中删除DOM元素_Javascript_Angularjs - Fatal编程技术网

Javascript 访问尚未编译的指令';从控制器中删除DOM元素

Javascript 访问尚未编译的指令';从控制器中删除DOM元素,javascript,angularjs,Javascript,Angularjs,我有一个在Angular编译指令之前执行的控制器。控制器需要操作仅在编译指令后才存在的DOM元素。如果DOM元素还不在DOM中,我如何选择它来操作它 下面是一个人为的例子来说明这一点。假设我有以下标记: <div ng-controller="CustomerCtrl"> <div customer-list></div> </div> CustomerCtrl看起来像: .controller('CustomerCtrl', funct

我有一个在Angular编译指令之前执行的控制器。控制器需要操作仅在编译指令后才存在的DOM元素。如果DOM元素还不在DOM中,我如何选择它来操作它

下面是一个人为的例子来说明这一点。假设我有以下标记:

<div ng-controller="CustomerCtrl">
    <div customer-list></div>
</div>
CustomerCtrl
看起来像:

.controller('CustomerCtrl', function() {
    var customerList = angular.element('[customer-list]'),
        firstCustomer = customerList.children('option:first');

    // firstCustomer is length === 0 at this point, so
    // this code does not work
    firstCustomer.prop('selected', 'selected');
});
我的解决方案是这样做:

.controller('CustomerCtrl', function($timeout) {
    var customerList = angular.element('[customer-list]');

    // this works
    $timeout(function() {
        customerList.children('option:first').prop('selected', 'selected');
    });
});

我想知道的是,使用
$timeout()?这方面有最佳实践吗?

您应该使用指令的链接函数来执行这种操作。那你就不用使用超时了。这种DOM操作实际上属于指令而不是控制器。控制器只是作用域的持有者,实际上不应该包含太多的应用程序/ui逻辑。
该链接保证在您的指令编译后被调用,因此如果您使用该链接,您应该很好。

您为什么还要这样做?就在第一个选项的属性上?无论如何,对于DOM操作,可以使用指令和编译/链接函数。不要将jQuery与angular一起使用。使用指令,您会遇到问题,因为您只是误用了控制器。
.controller('CustomerCtrl', function($timeout) {
    var customerList = angular.element('[customer-list]');

    // this works
    $timeout(function() {
        customerList.children('option:first').prop('selected', 'selected');
    });
});