如何指令调用如果包含指令的元素是通过一个角度控制器动态添加? [英] How directives are invoked If an element that contains a directive is added dynamically through an angular controller?
问题描述
在做一些搜索后我还没有发现这种坏习惯的信息。比方说,我有一个控制器的行为一样,(我知道这应该是一个指令,并在控制器,我们永远不会做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-点击触发的addElement()。如何在现有自动调整指令,将触发到实际工作。相比之下输入元素preexist并具有自动调整指令,做工精细。我也试过$ scope.apply(函数(){});周围的缩进code创建输入元素,它会导致类型错误:未定义不是一个函数:/
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 :/
推荐答案
根据穆罕默德Shahrouri的评论上面,我不得不注入在控制器中的 $编译
依赖和我不得不添加 $编译(输入)($范围内);
结尾:
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);
}
}
]);
这篇关于如何指令调用如果包含指令的元素是通过一个角度控制器动态添加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!