I want to share my service data b/w two controllers and my controllers are independent. How can I achieve this?
Here is my service:
angular.module("myApp").service('emt', function($http,$rootScope)
{
this.value1 = "";
this.value2 = "";
});
Here is my first controller:
angular.module('myApp').controller('emitCtrl', function($scope,emt,$modal,$rootScope){
$scope.user=emt;
$scope.myArray=[];
$scope.send=function(user){
$scope.myArray.push({value1:$scope.user.value1,value2:$scope.user.value2});
console.log($scope.user);
$scope.user.value1="";
$scope.user.value2="";
//firing an event towords upword direction using emit.
$rootScope.$emit('myEmitEvent', 'emt'); // emt is the name of service.
};
//modeal for show emit data
$scope.open=function(){
alert("hello its emit !");
$modal.open({
templateUrl: '../../../view/emitPageModal.html',
controller: 'myEventCtrl'
});
};
});
Here is my second controller:
angular.module('myApp').controller('myEventCtrl', function($scope,emt,$modalInstance,$rootScope){
$scope.demo=false;
$scope.ok = function () {
$scope.demo=true;
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
// for catching an event raised by emit
$rootScope.$on('myEmitEvent', function (event, data) {
$scope.myemitedData=data.emt;
console.log(data.emt);
console.log($scope.myemitedData);
// 'Some data'
});
});
Here is my modal:
<div class="modal-header" ng-hide="demo">
<h4>Modal Dialog</h4>
</div>
<div class="modal-body">
<p>Example paragraph with some text.</p>
<p>Your name is :{{user.value1}}</p>
<p>Your number is :{{user.value2}}</p>
</div>
<div class="modal-footer">
<button class="btn btn-success" ng-click="ok()">Okay</button>
<button class="btn" ng-click="cancel()">Cancel</button>
</div>
Services are nothing but entities that can be shared. These can have complex objects, functions etc. In order to share them services has to return them like following :
angular.module("myApp").service('emt', function($http, $rootScope) {
var myObj = {
value1: "",
value2: ""
}
var func = function(){
console.log('test')
}
return {
obj: myObj,
publicFun : func
}
});
Now the variable myObj will be available wherever emt is injected.
angular.module('myApp').controller('emitCtrl', function($scope,emt,$modal,$rootScope){
$scope.user=emt.obj;
});
This emt.obj will always have the latest value in any controller it is shared in.