Reputation: 33
I have a form made up of directives. Two parts of this form are identical in input fields, selects, and check boxes. I made a directive using isolate scope and controllerAs syntax (with bindToController=true) where the controller has a method that fires from an ngChange on the checkBox. My problem is that the controller alias I assign 'this' to in the controller is fired twice, once for each directive. The second time through that controller alias name, in my example case 'ctrlVm', is overwritten with the second scope.
A simpler directive and controller that duplicate this problem is:
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);
}
}
}
A full demo with the above code and html can be found at:
http://plnkr.co/edit/TdZgadsmVQiZhkQQYly1?p=preview
I am basically calling the directive twice and expecting them to result in a "one" or a "two", depending on which box you click in. But as you can see, the first controller was "overwritten" by the second and regardless of which box you check it fires the second directive's function and adds a "two" to the array regardless of which box you click.
I have done exhaustive searching all day, learning some other things along the way, but have not found more than a couple references related to this problem and both of those seemed to imply a need for either two different directives that have different controllerAs alias names or a directive that accepts a variable name for the controllerAs name. Both of those solutions seem to require two different views since my view includes the use of the controllerAs alias (which would now be different for the two directives).
So is there a way to do this, reusing the controller and with controllerAs syntax, and have the example runTest() function exist separately for the two directives? Thank you for any help.
Upvotes: 3
Views: 647
Reputation: 6841
In your controller for the directive you don't declare the variable ctrlVm.
So change:
function controller() {
ctrlVm = this;
ctrlVm.runTest = runTest;
function runTest() {
ctrlVm.myArray.push(ctrlVm.boundObject.first);
}
}
To:
function controller() {
var ctrlVm = this;
ctrlVm.runTest = runTest;
function runTest() {
ctrlVm.myArray.push(ctrlVm.boundObject.first);
}
}
http://plnkr.co/edit/Qab1lpgbrK8ZRLZiRdaQ?p=preview
Upvotes: 0