ng-controller with ng-include doesn't bind correctly

122 Views Asked by At

I have this A component, with a.html and a.ts files.

Inside a.html, the controller defined in a.ts (AController) is called ar.

Also, inside a.html call b.html with ng-include.

<div ng-include="'/public/templates/b.html'"
     ng-controller="AController as ctr"
     ng-if="someBoolean">

Inside b.html, there are a lot of divs concatenated, and they refer to the controller as ctr.

<div class="cardContent horizontalLayout" style="min-height:54px">
  <span>Last Name</span>
  <div class="flex"></div>
  <div class="horizontalLayout" ng-style="{'width': inputWidth}">
    <input  type="text" 
            class="materialInput flex smallPlaceholder" 
            ng-model="ctr.tempItem.lastName" 
            placeholder="Write here...">
  </div>
</div>
<div class="cardContent horizontalLayout" style="min-height:54px">
  <span>First Name</span>
  <div class="flex"></div>
  <div class="horizontalLayout" ng-style="{'width': inputWidth}">
    <input  type="text" 
            class="materialInput flex smallPlaceholder" 
            ng-model="ctr.tempItem.firstName" 
            placeholder="Write here...">
  </div>
</div>
(...)

The problem: for some reason, the binding isn't working. b.html doesn't recognize ctr as AController, but ng-include works fine because the template is rendered.

Extra data: if I change the calling to b.html with the following, it works fine:

<div ng-include="'/public/templates/b.html'"
     ng-controller="AController as ar"
     ng-if="someBoolean">

So, it only works if I name the controller sarasa in b.html the same as in a.html. I don't want this, because b.html must be polimorfic to be reutilizable.

Why I'm not using a directive? For two reasons:

  1. There is no logic here, it's only html.
  2. I tried but I need replace property in true because the styles in a.html should apply in the divs too, and with replace in true I can't write more than one element because AngularJS doesn't like that. I'm exploring transclude option, but still is not a good idea using something so big to do this.

Edit:

This is something similar to my controller:

namespace C {  

  class CController {
    
    public someProperty: string;

    constructor(private $scope: ng.IScope) {}  

    public someMethod(){}

  }
    
  App.controller('AController', ['$scope', CController]);
};

CController is the controller of c.html, which includes a.html with ng-include. So, CController is the controller of a.html, as it's written in the last line (App.controller(...))

0

There are 0 best solutions below