如何调用指令 如果包含指令的元素是通过 angular 控制器动态添加的? [英] How directives are invoked If an element that contains a directive is added dynamically through an angular controller?

查看:24
本文介绍了如何调用指令 如果包含指令的元素是通过 angular 控制器动态添加的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在进行了一些搜索之后,我在这种不良做法中没有找到太多信息.假设我有一个行为类似的控制器(我知道它应该是一个指令,并且在控制器中我们从不进行 DOM 操作,但我很好奇..)

After doing some search I haven't found much information in this bad practice. Let's say I have a controller that behaves like that (I know it should have been a directive and that in controllers we never do DOM manipulation but I am curious..)

angular.module('app').controller('test', ['$scope',
    function($scope) {
        $scope.addElement = function() {

            var input = document.createElement('input');
            input.type = "text";
            //directive
            input.setAttribute("autosize","autosize");
            input.setAttribute("ng-model","dummy");
            //[ append code ]
            input.focus();



        }
    }
]);

让我们假设我有一个通过 ng-click 触发 addElement() 的按钮.如何触发"现有的 autosize 指令以实际工作.相比之下,预先存在并具有 autosize 指令的输入元素工作正常.我也试过 $scope.apply(function() { });围绕创建输入元素的缩进代码并导致 TypeError: undefined is not a function :/

and let's assume that I have a button that triggers addElement() with ng-click. How the existing autosize directive will be "triggered" to actually work. In contrast input elements that preexist and have the autosize directive work fine. I also tried $scope.apply(function() { }); around the indented code that creates the input element and it causes TypeError: undefined is not a function :/

推荐答案

根据上面 Mohammad Shahrouri 的评论,我不得不在控制器中注入 $compile 依赖项,我不得不添加 $compile(input)($scope); 最后:

Based on Mohammad Shahrouri's comment above, I had to inject the $compile dependency in the controller and I had to add $compile(input)($scope); at the end:

angular.module('app').controller('test', ['$scope','$compile',
    function($scope, $compile) {
        $scope.addElement = function() {

            var input = document.createElement('input');
            input.type = "text";
            //contains directive
            input.setAttribute("autosize","autosize");
            input.setAttribute("ng-model","dummy");
            //[ append code ]
            input.focus();
            $compile(input)($scope);

        }
    }
]);

这篇关于如何调用指令 如果包含指令的元素是通过 angular 控制器动态添加的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆