How directives are invoked If an element that contains a directive is added dynamically through an angular controller?

一曲冷凌霜 提交于 2019-12-02 07:56:00

问题


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();



        }
    }
]);

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 :/


回答1:


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);

        }
    }
]);


来源:https://stackoverflow.com/questions/26447885/how-directives-are-invoked-if-an-element-that-contains-a-directive-is-added-dyna

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!