tuhin tuhin - 5 months ago 10
Javascript Question

ng-change is not firing when changing value from service

I need to reflect some changes to controller B (inside some event) when I make change at controller A. For that I am using a service.
When I am changing service value from FirstCtrl, ng-change is not firing at SecondCtrl. Is there anything I have missed or need to change?

Please note that I am using angular 1.5.6. and don't want to use watch or even scope.
Below is my code.



var myApp = angular.module('myApp', []);


myApp.factory('Data', function() {
return {
FirstName: ''
};
});

myApp.controller('FirstCtrl', ['Data',
function(Data) {
var self = this;
debugger
self.changeM = function() {
debugger
Data.FirstName = self.FirstName;
};

}
]);

myApp.controller('SecondCtrl', ['Data',
function(Data) {
var self = this;


self.FirstName = Data;

self.changeM = function() {
alert(1);
};
}
]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>

<div ng-app="myApp">

<div ng-controller="FirstCtrl as c">
<input type="text" ng-model="c.FirstName" data-ng-change="c.changeM()">
<br>Input is : <strong>{{c.FirstName}}</strong>

<div ng-controller="SecondCtrl as c1">
Input should also be here: {{c1.FirstName}}
<input type="text" ng-model="c1.FirstName" data-ng-change="c1.changeM()">
</div>
</div>
<hr>


</div>




Answer

As you dont want to use $scope trying modifying the code in order to use $emit and $on feature in angular js to communicate between two controllers. You can refer this link.

var myApp = angular.module('myApp', []);


myApp.factory('Data', function() {
  return {
    FirstName: ''
  };
});

myApp.controller('FirstCtrl', ['Data',
  function(Data) {
    var self = this;
    debugger
    self.changeM = function() {
      debugger
      //Data.FirstName = self.FirstName;
      Data.$on('emitData',function(event,args){
        Data.FirstName=args.message
        document.write(Data.FirstName)
      })
    };

  }
]);

myApp.controller('SecondCtrl', ['Data',
  function(Data) {
    var self = this;
    self.FirstName = Data;
    self.changeM = function() {
       Data.$emit('emitData',{
        message:Data.FirstName
      })

    };
  }
]);
Comments