Kindergart Kindergart - 5 months ago 14x
AngularJS Question

AngularJS, $destroy event don't propagate changes for double binded parameters

I have a simple directive with an isolated scope that is responsible to change a a value. When it is destroyed i want the value to be set to undefined. However the changes in the destroy function doesn't propagate changes.

Here is the code.
And again the problem is that outData is not set to 'undefined' outside this scope

scope: {
outData: '=ngModel',
link: function (scope, elem, attars) {
scope.$on('$destroy', function () {
scope.outData = undefined;

I made a plunker to demonstrate the problem.
Is this a bug? If not, is there a '$preDestroy' event to listen for?


Apparently angular brodcast the $destroy event from inside the $destroy function and before it returns it sets both $apply and $digest to noops. Meaning changes can not be noticed in the digest cycle (as far as my understanding goes). I ended up creating a setter method by evaluating the actual object on the parent scope like so

 link: function (scope, elem, attrs, ngModelCtrl) {

   var dotPos = attrs.ngModel.lastIndexOf('.');
   var objString = attrs.ngModel.substr(0,dotPos);
   var paramString = attrs.ngModel.substr(dotPos+1,attrs.ngModel.length);
   var object = scope.$parent.$eval(objString);

   function setModel(val){
       object[paramString] = val

   scope.$on('$destroy', function () {

and then calling it in on the $destroy event.

!OBS! This only works when you use a object on your ng-model

<tvx-select ng-model="anyObject.value" ... />

It will not work for

<tvx-select ng-model="value" ... />