Use object of controller in another controller in angularjs - angularjs

I have two controller Controller A and controller B . controller A has an object $scope.operation={}; which is a json containing details.
In controller B I want to compare the detail of this json object and then run a function in COntroller B .How to achieve this..Thanks

Use a factory/service to store the operations array, whenever the value changes in the ControllerA controller update the values in service.
myApp.factory('myService', [function() {
var operations = {};
return {
getOperations: function() {
return operations
},
setOperations: function(op) {
operations = op;
},
}
}])
.controller('ControllerA', [function($scope, myService) {
$scope.operations = {};
$scope.$watch(function() {
return $scope.operations;
}, function() {
myService.setOperations($scope.operations);
});
}])
.controller('ControllerB', [function($scope, myService) {
$scope.operations = myService.getOperations();
}]);

Related

Update a $scope object from run function in AngularJS

I have my notification listener in the run function. When a notification is received I need to update a object present in $scope with a parameter present in notification object.
angular.module('app', ['ionic', 'chatsCtrl'])
.run(function($state, $ionicPlatform) {
window.FirebasePlugin.onNotificationOpen(function(notification) {
// Need to append this notification.parameter to a scope variable present in a controller
}
}
.controller('chatsCtrl', function($scope) {
// $scope.chats
});
How can I go about doing this? I don't want to use $rootScope object as $scope.chat object will get very heavy.
Thanks
you can't call scope variables/functions inside run block. since you don't want to use rootscope my suggestion is to create a service and assign values to a particular method in that service from the run block. Then get that value from the controller using the same service.
angular.module('app', ['ionic', 'chatsCtrl'])
.run(function($state, $ionicPlatform) {
window.FirebasePlugin.onNotificationOpen(function(notification) {
sampleService.setData(notification)
}
}
.controller('chatsCtrl', function($scope,sampleService) {
$scope.chats = sampleService.getData()
});
.factory('sampleService', function() {
var data;
return {
getData : function(){ return data},
setData: function(param){ data = param},
}
});

View not updating when using $controller service in angular

I have two controllers. The view is tied to the firstCtrl. I'm trying to run the function in the second one so the view is updated. Function runs but view not updated. Any ideas?
<div>{{people.length}}</div>
angular.module('myApp').controller('firstCtrl', function($scope, $http) {
var self = this;
$scope.people = [];
function getData() {
$http.get('/people').then(function(res) {
$scope.people = res.data;
});
}
getData();
$scope.getData = getData;
self.getData = function(){
$scope.getData();
};
return self;
});
angular.module('myApp').controller('secondCtrl', function( $controller, $scope, $http) {
var firstCtrl= $controller('firstCtrl', { $scope: $scope.$new() });
firstCtrl.getData(); //This runs but view is not updated above.
});
I think your code has some problem with the $scope. So instead of pass data directly in the firstCtrl. I pass a callback to getData function and assign data to $scope.people in the callback.
Here is the working Plunker:
> http://plnkr.co/edit/QznxFL

Angular calling shared service data update in controller

I am trying to write some very primitive angular code with 2 controllers and 1 service.
So when I call shared service from controller 1 and update data, I want to use same in my controller 2 $scope so that controller 2 $scope value can reflect on my DOM.
App.controller('oneCtrl', function($scope, $uibModal, $log, sharedProperties) {
// Call a new DOM element to so that ModalInstanceCtrl will be called
// Once controller 2 finishes, I want to update a $scope variable here
// $scope.projectList = getProjectList();
});
App.controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, sharedProperties) {
// This is a new modal which uses sharedProperties
// Update setProjectList() in service
});
App.service('sharedProperties', function() {
var projectList = new Array();
return {
getProjectList: function() {
return projectList;
},
setProjectList: function(value) {
projectList.push(value);
},
}
});
Once controller 2 calls setProjectList(). I want to auto update $scope value in controller 1 using getProjectList()
Please let me know how I can do that? Also do let me know if any further details needed on same.
A service in angular is a singleton so if you change data on the service it will be reflected whenever you call that service.
var app = angular.module('plunker', []);
app.controller('FirstCtrl', function($scope, userData) {
$scope.favoriteBook = userData.favoriteBook;
$scope.getFavoriteBook = function(){
$scope.favoriteBook = userData.favoriteBook;
}
});
app.controller('SecondCtrl', function($scope, userData) {
$scope.changeBook = function(){
userData.favoriteBook = 'The Hobbyt';
}
});
app.factory('userData', function(){
var favoriteBook = 'Harry Potter';
return{
favoriteBook : favoriteBook
}
})
Here you got a service that exposes an object, you can change the value of that object in the second controller and see it reflected in the first controller. Call changeBook(), and then getFavoriteBook()
This is the plunker:
the plunker

AngularJS how to get actual factory's data in controller?

I have the factory, when i get socket messages.
How i can get returned factory's actual data in my controller ?
Help please.
app.factory('socket',['$rootScope', function($rootScope) {
connection.open();
var connection = new autobahn.Connection({
url: 'wss://site.com:6555/',
realm: 'realm'
});
var collection = {
'topic1': [],
'topic2': []
};
function onevent(args) {
console.log("Event:", args[0]);
collection.topic1.push(args[0]);
}
connection.onopen = function(session) {
session.subscribe(userid, onevent);
}
return {
collection: collection
}
}]);
The factory cannot push data to a controller, but the controller can pull from the factory. To do so, inject the factory into the controller:
app.controller('yourController', ['$scope', 'socket', function($scope, socket) {
...
$scope.yourControllerCollection = socket.collection;
...
});
If you want the controller to auto-update when the socket factory receives an event and updates the collection, you can always inject the $rootScope into the factory and $emit an event that your controller can listen to. Something like:
app.factory('socket',['$rootScope', function($rootScope) {
...
function onevent(args) {
console.log("Event:", args[0]);
collection.topic1.push(args[0]);
$rootScope.$emit('SocketCollectionUpdated', collection); // Note that you can name your event whatever you want.
}
...
}]);
app.controller('yourController', ['$rootScope', '$scope', 'socket', function($rootScope, $scope, socket) {
...
$scope.yourControllerCollection = socket.collection;
$rootScope.$on('SocketCollectionUpdated', function (event, data) {
$scope.yourControllerCollection = data;
});
...
});
You want to inject the factory in the controller where you want to use the data. Here's a basic example of communicating data from factory to a controller.
app.factory('sharedData', function() {
return {
name: 'Daniel'
};
});
Then in your controller you can simple set this data object from the factory to the $scope.
app.controller('MainController', function($scope, sharedData) {
$scope.data = sharedData;
});
So in your case simply make a controller and inject the sockets factory, like this
app.controller('sockets', function($scope, sockets) {
$scope.collection = collection;
});

AngularJS update view with service/model changes using $q promises

I'm trying to load data from a service and update the view using $q, but it's not working. It works if I put the http call inside the controller, but I'd prefer it be part of the service.
Any help? Also, is there a better way to do this instead of promises?
Demo and code below.
---------- Fiddle Demo Link ----------
View
<div ng-init="getData()">
<div ng-repeat="item in list">{{item.name}}</div>
</div>
Controller
.controller('ctrl', ['$scope', 'dataservice', '$q', function ($scope, dataservice, $q) {
$scope.list = dataservice.datalist;
var loadData = function () {
dataservice.fakeHttpGetData();
};
var setDataToScope = function () {
$scope.list = dataservice.datalist;
};
$scope.getData = function () {
var defer = $q.defer();
defer.promise.then(setDataToScope());
defer.resolve(loadData());
};
}])
Service
.factory('dataservice', ['$timeout', function ($timeout) {
// view displays this list at load
this.datalist = [{'name': 'alpha'}, {'name': 'bravo'}];
this.fakeHttpGetData = function () {
$timeout(function () {
// view should display this list after 2 seconds
this.datalist = [{'name': 'charlie'}, {'name': 'delta'}, {'name': 'echo'}];
},
2000);
};
return this;
}]);
No need for ngInit or $q. This is how you should do it.
You should also not expose dataservice.list to the controller. That should be private to dataservice, which will contain most of the logic to determine whether to send the controller the existing list or update the list and then send it.
angular.module('app', [])
.controller('ctrl', ['$scope', 'dataservice', function ($scope, dataservice) {
loadData();
function loadData() {
dataservice.fakeHttpGetData().then(function (result) {
$scope.list = result;
});
}
}])
.factory('dataservice', ['$timeout', function ($timeout) {
var datalist = [
{
'name': 'alpha'
},
{
'name': 'bravo'
}
];
this.fakeHttpGetData = function () {
return $timeout(function () {
// Logic here to determine what the list should be (what combination of new data and the existing list).
datalist = [
{
'name': 'charlie'
},
{
'name': 'delta'
},
{
'name': 'echo'
}
];
return datalist;
},
2000);
};
return this;
}]);
Firstly, don't use ng-init in this way. As per the docs:
The only appropriate use of ngInit is for aliasing special properties
of ngRepeat, as seen in the demo below. Besides this case, you should
use controllers rather than ngInit to initialize values on a scope.
Secondly, promises are the perfect thing to use in this case, but you don't need to touch $q, as $http calls return promises for you.
To do this properly, simply return the $http result from the service:
this.getDataFromService = function() {
return $http(/* http call info */);
};
Then, inside you controller:
dataservice.getDataFromService().then(function(result){
$scope.list = result.data;
});
Also here is the updated fiddle: http://jsfiddle.net/RgwLR/
Bear in mind that $q.when() simply wraps the given value in a promise (mimicking the response from $http in your example).

Resources