Angular 1.5 component calling ng-change infinitily

1.3k views Asked by At

I have a component, lets say comx,

angular.component('comx', {
    templateUrl: 'someUrl',
    bindings: {
       model: '=',
       onChng: '='
    } 
}

and its html is

<input ng-model="vm.model" ng-change="vm.onChng">

and I'm adding this component in other template like

<comx model="vm.data" on-chng="vm.test(vm.data)">

vm.test = function (val) {
   console.log(val);  // val is printing infinitly
}

The above function's console is keep on printing

1

There are 1 answers

1
georgeawg On

@pankj: why not using & for expression?

@amir: tried that already, but weirdly its giving previous data of vm.data not the new one.

That happens because two-way = binding uses a watcher to transfer the data from isolate scope to parent scope. That happens on the dirty-checking cycle after the ng-change operation.

To provide the isolate scope value immediately, expose it as a local variable:

angular.component('comx', {
    template: '<input ng-model="$ctrl.model" '+
              '       ng-change="$ctrl.onChng({$model: $ctrl.model})">',
    bindings: {
       model: '=',
       onChng: '&'
    } 
});

Usage:

<comx model="vm.data" on-chng="vm.test($model)">
</comx>
vm.test = function (val) {
   console.log(val);
};

By exposing the model as a local variable, it is available immediately for the function in the parent scope.

The DEMO on JSFiddle.