angularjs not using $rootscope and $broadcast - javascript

So basically I'm trying to find a way to prevent using $rootscope ,$broadcast and $apply. Let me show you the code first:
app.controller('firstController', function ($scope, ServiceChatBuddy, socketListeners){
$scope.ChatBuddy = ServiceChatBuddy;
$scope.$on('user delete:updated', function (event, id) {
$scope.ChatBuddy.users[id]['marker'].setMap(null);
delete $scope.ChatBuddy.users[id];
});
$scope.$on('loadPosition:updated', function (event, data) {
$scope.$apply(function () {
$scope.ChatBuddy.users[data.id] = data.obj;
});
// and a bunch more like these
});
})
the socketListeners is a 3rd party libary (socket.io )which I implemented in a factory which will broadcast data when an event has occured
socketModule.factory('socketListeners', function ($rootScope, decorateFactory) {
var sockets = {};
var socket = io.connect('http://localhost:8000');
sockets.listen = function () {
socket.on('loadPosition', function (data) {
$rootScope.$broadcast('loadPosition:updated', data)
});
socket.on('client leave', function (id) {
$rootScope.$broadcast('user delete:updated', id);
});
// and a bunch more of these
});
As you can see the code exist alot of $rootscope $broadcasts and $apply;
So I'm struggling to find a way to do this more 'professional'. Any hints tricks best practices are absolutely welcome! cheers

Try this https://github.com/btford/angular-socket-io
socket.js (service)
angular.module('app')
.service('socket', function (socketFactory) {
var socket = io.connect('http://localhost:8000');
var mySocket = socketFactory({
ioSocket: socket
});
return mySocket;
});
firstController.js
app.controller('firstController', function ($scope, socket){
socket.forward('user delete:updated', $scope);
socket.forward('loadPosition:updated', $scope);
$scope.$on('user delete:updated', function (event, id) {
$scope.ChatBuddy.users[id]['marker'].setMap(null);
delete $scope.ChatBuddy.users[id];
});
$scope.$on('loadPosition:updated', function (event, data) {
$scope.$apply(function () {
$scope.ChatBuddy.users[data.id] = data.obj;
});
// and a bunch more like these
});
});
when scope is destroyed, listeners are destroyed too :)

Related

Setting value of dropdown programmatically

I have a directive which I want to change the value of on a click event. This is the controller that the click event is being triggered (I have removed all irrelevant code) :
(function () {
"use strict";
//getting the existing module
angular.module("app")
.controller("teamsController", teamsController);
//inject http service
function teamsController($scope, $http, divisionService, $rootScope) {
$scope.divisions = divisionService.all();
var vm = this;
vm.teams = [];
vm.newTeam = {};
vm.editTeam = function (team) {
$rootScope.$broadcast('someEvent', [team.division]);
}
And here is where the event is being captured :
(function () {
"use strict";
//getting the existing module
angular.module("app")
.controller("divisionsController", divisionsController)
.directive("divisionDropdown", divisionDropdown);
//inject http service
function divisionsController($http, $scope, divisionService, $rootScope) {
$scope.divisions = divisionService.all();
$rootScope.$on('someEvent', function (event, selectedDiv) {
alert(selectedDiv);
$rootScope.selectedDivision = selectedDiv;
});
};
function divisionDropdown() {
return {
restrict: "E",
scope: false,
controller: "divisionsController",
template: "<select class='form-control' ng-model='selectedDivision' ng-options='division.divisionName for division in divisions' required>\
<option style='display:none' value=''>{{'Select'}}</option>\
</select>"
};
}
})();
And this is the divisionService, which I am using to populate the dropdown intially :
app.factory("divisionService", function ($http) {
var divisions = [];
var errorMessage = "";
var isBusy = true;
//matched to verb, returns promise
$http.get('http://localhost:33201/api/Divisions')
.then(function (response) {
//first parameter is on success
//copy response.data to vm.divisions (could alternatively use a foreach)
angular.copy(response.data, divisions);
}, function (error) {
//second parameter is on failure
errorMessage = "Failed to load data: " + error;
})
.finally(function () {
isBusy = false;
});
return {
all: function () {
return divisions;
},
first: function () {
return divisions[0];
}
};
});
But I am not able to get the selectedDivision in the dropdown to change on the click event. Can anybody tell me how do I refer to it and reset it? I am not that familiar with scoping in Angular so my usage of $scope and $rootScope is possibly where the issue lies.

Where to place internal functions of angular controller?

AngularJS code style question.
I have an Angular module:
angular.module('module', [])
.controller('ModuleCtrl', function ($scope) {
var fnc = MenuControllerFunctions;
$scope.onBtnPressed = fnc.handlerFnc();
})
;
var MenuControllerFunctions = {
handlerFnc: function(){
return function() {
console.log('Button pressed')
}
}
};
Where should i place handlerFnc function?
In external variable (like here) or somewhere else?
Is any way to place it in module but not in '.controller' section?
In my opinion , you have to do like this
angular.module('module', [])
.controller('MenuController', MenuController);
MenuController.$inject(['$scope']);
function MenuController ($scope) {
$scope.onBtnPressed = handlerFnc;
function handlerFnc(){
console.log('Button pressed')
}
};

Why is my object not updated in the view in Angular?

I have SignalR working in my application:
app.run(['SignalRService', function (SignalRService) {}]);
SignalRService:
app.service("SignalRService", ['$rootScope', function ($rootScope) {
var masterdataChangerHub = $.connection.progressHub;
if (masterdataChangerHub != undefined) {
masterdataChangerHub.client.updateProgress = function (progress) {
$rootScope.$broadcast('progressChanged', progress);
}
masterdataChangerHub.client.completed = function (result) {
$rootScope.$broadcast('taskCompleted', result);
}
}
$.connection.hub.start();
}]);
As you can see I throw an event when a SignalR method gets invoked. This all works fine. However, on 1 directive, my data won't get updated. Here's the code:
app.directive('certificateDetails', ['CertificateService', 'TradeDaysService', 'DateFactory', function (CertificateService, TradeDaysService, DateFactory) {
return {
restrict: 'E',
templateUrl: '/Certificate/Details',
scope: {
certificateId: '=',
visible: '=',
certificate: '=',
certificateSaved: '&'
},
link: function (scope, element, attributes) {
scope.certificateFormVisible = false;
scope.showCancelDialog = false;
scope.splitCertificateFormVisible = false;
scope.partialPayoutFormVisible = false;
scope.$on("taskCompleted", function (evt, response) {
console.log(response);
CertificateService.getCertificateById(scope.certificate.Id).then(function (response) {
scope.certificate = response;
});
});
scope.$watch('visible', function (newVal) {
if (newVal === true) {
scope.showButtonBar = attributes.showButtonBar || true;
if (scope.certificateId) {
getCertificateById();
}
}
});
function getCertificateById() {
CertificateService.getCertificateById(scope.certificateId).then(function (response) {
scope.certificate = response;
});
};
}
}
}]);
The weird thing is, when I have my console open (I use Chrome) on the network tab, I can see that the directive makes a request to the right URL with the right parameters. Also, when the console is open, my data is updated in the view. However, and this is the strange part, when I close the console, nothing happens! It doesn't update the view..
I have also tried to put the code inside the taskCompleted event in a $timeout but that doesn't work either.
Could someone explain why this happens and how to solve this problem?
EDIT I
This is how the getCertificateById looks like in my CertificateService
this.getCertificateById = function (id) {
var promise = $http.post('/Certificate/GetById?id=' + id).then(function (response) {
return response.data;
});
return promise;
};
Handling SignalR events will execute out of the Angular context. You will need to $apply in order to force digest for these to work. I'd try to call $apply on $rootScope after the $broadcast:
var masterdataChangerHub = $.connection.progressHub;
if (masterdataChangerHub != undefined) {
masterdataChangerHub.client.updateProgress = function (progress) {
$rootScope.$broadcast('progressChanged', progress);
$rootScope.$apply();
}
masterdataChangerHub.client.completed = function (result) {
$rootScope.$broadcast('taskCompleted', result);
$rootScope.$apply();
}
}
If this works then the issue definitely a binding issue between SignalR and Angular. Depending on what browser plugins you have installed, having the console open could trigger a digest for you.
On the sample listeners for this project (that binds SignalR and Angular), you can see that a $rootScope.$apply() is needed after handling on the client side:
//client side methods
listeners:{
'lockEmployee': function (id) {
var employee = find(id);
employee.Locked = true;
$rootScope.$apply();
},
'unlockEmployee': function (id) {
var employee = find(id);
employee.Locked = false;
$rootScope.$apply();
}
}
So, I'd assume that you would need to do the same.

AngularJS $emit does not fire the event after added code to unregister

I just found out how to communicate between controllers using $broadcast and $emit, tried it in my POC and it worked, sort of, the original problem described in this other post is still not solved but now I have another question, the event is being registered multiple times so I am trying to unregister it the way I've seen it in multiple posts here on SO but now the event won't fire. The code is as follows:
tabsApp.controller('BasicOverviewController', function ($scope, $location, $rootScope) {
var unbind = $rootScope.$on('displayModal', function (event, data) {
if (data.displayModal) {
alert("I want to display a modal!");
var modal = $('#basicModal');
modal.modal('toggle');
}
});
$scope.$on('$destroy', function () {
unbind();
});
});
tabsApp.controller('SportsController', function SportsController($scope, $location, $rootScope) {
$scope.goToOverview = function (showModal) {
$location.path("overview/basic");
$rootScope.$emit('displayModal', { displayModal: showModal })
};
});
If I remove the
var unbind = ...
the event fires and I can see the alert. As soon as I add the code to unregister the event, the code is never fired. How can the two things work together?
Could you just pull out unbind into its own function, and use it in both like this?
tabsApp.controller('BasicOverviewController', function ($scope, $location, $rootScope) {
var unbind = function (event, data) {
if (data.displayModal) {
alert("I want to display a modal!");
var modal = $('#basicModal');
modal.modal('toggle');
}
};
$rootScope.$on('displayModal', unbind);
$scope.$on('$destroy', unbind);
});
I could be wrong but my guess would be that the BasicOverviewController isn't being persisted and it's scope is being destroyed before the SportsController gets a chance to utilize it. Without a working example, I can't deduce much more. If you want to maintain this on $rootScope then a possible pattern would be:
if (!$rootScope.displayModalDereg) {
$rootScope.displayModalDereg = $rootScope.$on('displayModal', function (event, data) {
if (data.displayModal) {
alert("I want to display a modal!");
var modal = $('#basicModal');
modal.modal('toggle');
}
});
This also allows you to check and see if there is an event registered so you can dereg it if needed.
if ($rootScope.displayModalDereg) {// this event has been registered
$rootScope.displayModalDereg();
$rootScope.dispalyModalDereg = undefined;
}
I would heavily suggested creating a displayModal directive that persists all of this instead of maintaining it on $rootScope. Obviously you would still $emit, or better yet, $broadcast from $rootScope, just not persist the dereg function there.
Here is an example of a modal directive I once wrote:
/**
*
* Modal Directive
*/
'use strict';
(function initModalDrtv(window) {
var angular = window.angular,
app = window.app;
angular.module(app.directives).directive('modalDrtv', [
'$rootScope',
function modalDrtv($rootScope) {
return {
restrict: 'A',
scope: {},
templateUrl: '/templates/modal.html',
replace: true,
compile: function modalCompileFn(tElement, tAttrs) {
return function modalLinkFn(scope, elem, attrs) {
scope.show = false;
scope.options = {
'title': '',
'message': '',
'markup': undefined,
'buttons': {
showCancel: false,
showSecondary: false,
secondaryAction: '',
primaryAction: 'Ok'
},
'responseName': ''
};
scope.respond = function(response) {
var r = '';
if (response === 1) {
r = scope.options.buttons.primaryAction;
} else if (response === 2) {
r = scope.options.buttons.secondaryAction;
} else {
r = response;
}
$rootScope.$broadcast(scope.options.responseName, r);
scope.show = false;
};
scope.$on('initIrpModal', function(event, data) {
if (angular.isUndefined(data)) throw new Error("Data missing from irp modal event");
scope.options.title = data.title;
scope.options.message = data.message;
scope.options.buttons.showCancel = data.buttons.showCancel;
scope.options.buttons.showSecondary = data.buttons.showSecondary;
scope.options.buttons.secondaryAction = data.buttons.secondaryAction;
scope.options.buttons.primaryAction = data.buttons.primaryAction;
scope.options.responseName = data.responseName;
scope.show = true;
});
}
}
}
}
]);
})(window);
This directive utilizes one modal and let's anything anywhere in the app utilize it. The registered event lives on its isolate scope and therefore is destroyed when the modal's scope is destroyed. It also is configured with a response name so that if a user response is needed it can broadcast an event, letting the portion of the app that initialized the modal hear the response.

Easily create multiple socket.io events in node.js

Just a quick question around optimisation and DRY. I have my node server and everything works as it should, but I want to know how to clean up for future devs. I have a set of events being assigned like so:
var debug = true;
io.sockets.on('connection', function (socket) {
console.log('User connected!');
socket.on('event-one', function (data) {
if(debug) { console.log('Event 1!'); }
socket.broadcast.emit('event-one', data);
});
socket.on('event-two', function (data) {
if(debug) { console.log('Event 2!'); }
socket.broadcast.emit('event-two', data);
});
socket.on('event-three', function (data) {
if(debug) { console.log('Event 3!'); }
socket.broadcast.emit('event-three', data);
});
});
As you can see I'm repeating the socket.on() method. Is there a more efficient way of writing this? I tried a simple array with a for loop but the events stopped working.
Any input would be appreciated.
Thanks.
Not sure why your loop didn't work, this works just fine:
var debug = true;
var events = [ 'event-one', 'event-two', 'event-three' ];
io.sockets.on('connection', function (socket) {
events.forEach(function(ev) {
socket.on(ev, function(data) {
if (debug) {
console.log('got event:', ev);
}
socket.broadcast.emit(ev, data);
});
});
});

Categories

Resources