简体   繁体   English

如何将DOM元素(带有控制器)动态添加到AngularJS范围

[英]How to add DOM element (with controller) into AngularJS scope dynamically

I am trying to build an application (using AngularJS) which allows me to drag a complex HTML element which MAY include angular controller calls from a palette into a div. 我正在尝试构建一个应用程序(使用AngularJS),该应用程序允许我拖动一个复杂的HTML元素,该元素可能包括从面板到div的角度控制器调用。

The drag/drop portion is working, however I am not able to get the element clone into the scope. 拖放部分正在工作,但是我无法将元素克隆放入范围。

I have a JSFiddle demonstrating the problem here: http://jsfiddle.net/gdharley/h4AcC/ 我有一个JSFiddle在这里演示问题: http : //jsfiddle.net/gdharley/h4AcC/

Basically, when the element is dropped, I am emitting an event that is picked up by the mainController. 基本上,当元素被删除时,我发出一个由mainController拾取的事件。

$scope.$on('my-created', function (ev, val) {
    $scope.items.splice(val.to, 0, {
        name: val.name
    });
    var myInjector = angular.injector(["ng", "plunker"]);
    var $compile = myInjector.get("$compile"); // retrieve the compile service
    var fnLink = $compile(val); // returns a Link function used to bind element to the scope
    fnLink($scope);
})

I am then retrieving the compile service from the injector and compiling he element into the scope. 然后,我从注入器中检索编译服务,并将其元素编译到范围中。

While no errors are thrown, the clone of the element is not functional (ie adding contacts does not appear to call the add() function in the controller. 虽然没有引发任何错误,但是该元素的克隆不起作用(即,添加联系人似乎不会在控制器中调用add()函数)。

Any help appreciated. 任何帮助表示赞赏。 Thanks. 谢谢。 Greg 格雷格

No, you don't put things in the DOM with your controller. 不,您不会将任何东西放在控制器中。 You do it in a directive. 您可以在指令中执行。 Even then, you don't need any of that. 即使那样,您也不需要任何。 Just have your "add()" function add things to your model and use ng-repeat to output more. 只需让您的“ add()”函数向模型中添加内容,然后使用ng-repeat即可输出更多内容。

Everything you're doing should be based around changing a model. 您所做的一切都应基于更改模型。 It's hard for me to understand exactly what you're trying to achieve, but the result of a drag-drop should modify your model and angular can react based on watches or emits, but you shouldn't be compiling anything manually most of the time. 我很难确切地了解您要实现的目标,但是拖放的结果应该修改您的模型,并且角度可以根据手表或发射而做出反应,但是您不应该在大多数时候手动进行任何编译。

If you do need to compile do it inside your directive, not your controller. 如果确实需要编译,请在指令而不是控制器中执行。 Just inject the $compile service and call it that way. 只需注入$compile服务并以这种方式调用它即可。

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

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