In my form, I have directives that contain identical input fields, selects, and check boxes. To handle this, I created a directive with an isolate scope and controllerAs syntax using bindToController=true. The controller has a method triggered by an ngChange on the checkBox. However, I encountered an issue where the controller alias I assigned, 'ctrlVm', is overwritten by the second instance of the directive. This results in the runTest() function firing for both directives, instead of independently.
A simplified version of the problematic directive and controller looks like:
function myDirective() {
var directive = {
restrict: 'AE',
priority: 100,
require: 'ngModel',
scope: {
boundObject: '=boundObj',
myArray: '='
},
templateUrl: 'myTemplate.html',
controller: controller,
controllerAs: 'ctrlVm',
bindToController: true
};
return directive;
function controller() {
ctrlVm = this;
ctrlVm.runTest = runTest;
function runTest() {
ctrlVm.myArray.push(ctrlVm.boundObject.first);
}
}
}
To see the full demo showcasing this issue, visit:
http://plnkr.co/edit/TdZgadsmVQiZhkQQYly1?p=preview
Essentially, I expect clicking each box to result in either "one" or "two" being added to the array. However, due to the controller alias being overwritten, both instances behave the same way adding "two" regardless of the clicked box.
I have searched extensively but found limited solutions suggesting different aliases for controllers or dynamically setting the controllerAs name based on directives. Unfortunately, these approaches would require separate views as my current view utilizes controllerAs aliases. Is there a way to reuse the controller and maintain the expected functionality for each directive separately?