gpt4 book ai didi

javascript - Angular 1.5。如何使嵌入的模板绑定(bind)到组件范围

转载 作者:行者123 更新时间:2023-11-29 15:25:36 25 4
gpt4 key购买 nike

我正在使用具有通用验证和保存功能的表单组件。输入作为嵌入模板传递给表单,如下所示:

<form-editor entity="vm.entity">
<input ng-model="vm.dirtyEntity.name" required name="nameInput">
</form-editor>

问题是,ng-model 正在父虚拟机中创建 dirtyEntity 字段,而不是修改组件之一。将组件 Controller 定义为“formVm”没有帮助。

有没有办法强制嵌入的元素 ng-model 只改变组件的范围?

或者在嵌入的模板和组件 Controller 之间进行交互是否被认为是不正确的,永远不应该这样做?

最佳答案

基于 dfsq 的 plunkr,这里是您问题的解决方案:

在您的组件中,您以编程方式复制用于嵌入的元素并将它们添加到您的表单 Controller 中。

您可以使用 $transclude 服务以编程方式嵌入并将元素附加到表单,如下所示:

$transclude($scope, function(clone) {
$element.find('form').append(clone);
})

然后像这样将元素添加到表单 Controller :

$scope.testForm.$addControl($element);

在这种情况下,您需要将其包装在超时中,否则 Angular 将实例化您的 Controller 并且您的代码将运行,但是,表单 Controller 尚未实例化。

这是完整的片段,您可以找到一个 plunkr here

controller($scope, $element, $transclude, $timeout) {
// use a timeout to break javascript flow to allow a DOM update
$timeout(function() {
$transclude($scope, function(clone) {
$element.find('form').append(clone);

// take the form and add the elements to it
$scope.testForm.$addControl($element);
})
})
}

但是,请记住,您可能需要检查不是输入的元素。我不确定表单 Controller 对作为控件添加的图像的 react 有多稳健。

关于javascript - Angular 1.5。如何使嵌入的模板绑定(bind)到组件范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39466031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com