lexigren
lexigren

Reputation: 550

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:

<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. Defining components controller as "formVm" didn't help.

Is there way to force transcluded element ng-model to change only component's scope?

Or is it considered incorrect to interact between transcluded template and component controller, and shouldn't be never done?

Upvotes: 3

Views: 1478

Answers (1)

PerfectPixel
PerfectPixel

Reputation: 1968

Building on the plunkr of dfsq, here is a solution to your problem:

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($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.

Here is the complete snippet and you can find a 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);
    })
  })
}

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.

Upvotes: 1

Related Questions