简体   繁体   English

Angular 1.5。 如何使transcluded模板绑定到组件范围

[英]Angular 1.5. How to make transcluded template to bind to component scope

I'm using form component with common validation and saving functions. 我正在使用具有常见验证和保存功能的表单组件。 Inputs are passed to form as transcluded template, like so: 输入作为transcluded模板传递给form,如下所示:

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

The problem is, ng-model is creating dirtyEntity field in parent vm, instead of modifying the components one. 问题是,ng-model正在父vm中创建dirtyEntity字段,而不是修改组件之一。 Defining components controller as "formVm" didn't help. 将组件控制器定义为“formVm”没有帮助。

Is there way to force transcluded element ng-model to change only component's scope? 有没有办法强制转换元素ng-model只改变组件的范围?

Or is it considered incorrect to interact between transcluded template and component controller, and shouldn't be never done? 或者在被转换的模板和组件控制器之间进行交互被认为是不正确的,不应该永远不会这样做?

Building on the plunkr of dfsq, here is a solution to your problem: 建立在dfsq的plunkr上,这是一个解决您的问题的方法:

In your component, you programmatically copy the elements meant for transclusion and add them to your form controller. 在组件中,您以编程方式复制用于转换的元素,并将它们添加到表单控制器中。

You can programmatically transclude using the $transclude service and append the elements to the form like this: 您可以使用$ transclude服务以编程方式转换,并将元素附加到表单,如下所示:

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

Then you add the elements to your form controller like this: 然后将元素添加到表单控制器,如下所示:

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

In this case you need to wrap it in a timeout otherwise angular will instantiate your controller and your code will run, however, the form controller is not instantiated yet. 在这种情况下,您需要将其包装在超时中,否则angular将实例化您的控制器并且您的代码将运行,但是,表单控制器尚未实例化。

Here is the complete snippet and you can find a plunkr here 这是完整的片段,你可以在这里找到一个plunkr

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

However, keep in mind that you might need to check for elements that are not inputs. 但是,请记住,您可能需要检查不是输入的元素。 I am unsure how robust the form controller reacts to an image added as a control. 我不确定表单控制器对作为控件添加的图像的反应有多强大。

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

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