How to prevent $scope.$destroy? - angularjs

I want to prevent $scope.$destroy event in my nested controller in my page. I see the event object in callback function has method preventDefault, but it's not working as I expect.
$scope.$on('$destroy', function(event) {
event.preventDefault(); // don't working!
});
It is possible to prevent $destroy event?
plnkr Example

Related

$scope.$on Called several times

I am using
$rootScope.$broadcast("closeviewMultiUserMainDetail");
and using in by below
$rootScope.$on("closeviewMultiUserMainDetail", function (event) {
//other code
});
sometimes ‍‍$rootScope.$on Called several times.
How can this be prevented?
$rootScope event listeners are not destroyed automatically and are always listening. That is why $rootScope.$on is getting called several times. You need to destroy the event listener using $destroy.
You can define your event like this:
var closeviewMultiUserMainDetail = $rootScope.$on('closeviewMultiUserMainDetail', function(event) { });
You can then destroy it like this:
$scope.$on('$destroy', function() {
closeviewMultiUserMainDetail(); });

Angular $rootscope.$on where to activate deregistration function

I have event listeners activated by:
var unregisterSubscription = $rootScope.$on(event, handler);
The event is activated in component and/or directive.
I want the listener to listen when the user uses the scope of the listener, otherwise not.
now my question is where i activate the unregisterSubscription method?
You can create destroy event in controller.
$rootScope.$on('$destroy', function() {
unregisterSubscription(); // Call unregisterSubscription method.
});

How to handle $stateChangeSuccess event if multiple states have same controllers

I'm using a single controller in two states. If I navigate within these two states, and try to handle $stateChangeSuccess event, I'm facing an issue which is, in each state, the event is triggering twice.
$scope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
// some code...
});
I know that this is a game of $scope, but how can I handle it. Thanks in advance...
I believe you should be watching $stateChangeSuccess on the $rootScope like this instead:
$rootScope.$on('$stateChangeSuccess' function() {
//code
};
If that's not the case, here is some good information about controller scope. From that, you should be able to watch the two events: $viewContentLoaded and $destroy
$scope.$on('$viewContentLoaded', function() {
console.log('Stuff loaded');
});
$scope.$on('$destroy', function() {
console.log('Destroyed');
})
From there you should be able to determine the scope issue.

How to remove Cordova specific events outside Angular controller?

Imagine I have a controller which handles, for example, view changes:
function Controller($scope){
var viewModel = this;
viewModel.goBack= function(){
viewModel.visible = visibleLinks.pop(); //get last visible link
viewModel.swipeDirection = 'left';// for view change animation
}
}
But I want to handle it not only for example with HTML buttons inside <body>, but also with Back button on device. So I have to add Event Listener for deviceready event, and also explicit call $scope.$apply() in order to fact, that it is called outside of AngularJS context, like this:
document.addEventListener("deviceready", function(){
document.addEventListener("backbutton", function(){
viewModel.goBack();
$scope.$apply();
}, false);
}, false);
}
But I also want to follow (relatively :) ) new controllerAssyntax, cause this is recommended now e.g. by Todd Motto: Opinionated AngularJS styleguide for teams and it allows to remove $scope from controllers when things like $emit or $on are not used. But I can't do it, case I have to call $apply() cause my context is not Angular context when user clicks on device back button. I thought about creating a Service which can be wrapper facade for cordova and inject $scope to this service but as I read here: Injecting $scope into an angular service function() it is not possible. I saw this: Angular JS & Phonegap back button event and accepted solution also contains $apply() which makes $scope unremovable. Anybody knows a solution to remove Cordova specific events outside Angular controller, in order to remove $scope from controllers when not explicity needed? Thank you in advance.
I don't see a reason why to remove the $scope from the controller. It is fine to follow the best practice and to remove it if not needed, but as you said you still need it for $emit, $on, $watch.. and you can add it $apply() in the list for sure.
What I can suggest here as an alternative solution is to implement a helper function that will handle that. We can place it in a service and use $rootScope service which is injectable.
app.factory('utilService', function ($rootScope) {
return {
justApply: function () {
$rootScope.$apply();
},
createNgAware: function (fnCallback) {
return function () {
fnCallback.apply(this, arguments);
$rootScope.$apply();
};
}
};
});
// use it
app.controller('SampleCtrl', function(utilService) {
var backBtnHandler1 = function () {
viewModel.goBack();
utilService.justApply(); // instead of $scope.$apply();
}
// or
var backBtnHandler2 = utilService.createNgAware(function(){
viewModel.goBack();
});
document.addEventListener("backbutton", backBtnHandler2, false);
});
In my case I was simply forwarding Cordova events with the help of Angular $broadcast firing it on the $rootScope. Basically any application controller would then receive this custom event. Listeners are attached on the configuration phase - in the run block, before any controller gets initialized. Here is an example:
angular
.module('app', [])
.run(function ($rootScope, $document) {
$document.on('backbutton', function (e) {
// block original system back button behavior for the entire application
e.preventDefault();
e.stopPropagation();
// forward the event
$rootScope.$broadcast('SYSTEM_BACKBUTTON', e);
});
})
.controller('AppCtrl', function ($scope) {
$scope.$on('SYSTEM_BACKBUTTON', function () {
// do stuff
viewModel.goBack();
});
});
Obviously in the $scope.$on handler you do not have to call $scope.$apply().
Pros of this solution are:
you'll be able to modify an event or do something else for the entire application before the event will be broadcasted to all the controllers;
when you use $document.on() every time controller is instantiated, the event handler stays in the memory unless you manually unsibscribe from this event; using $scope.$on cares about it automatically;
if the way a system dispatches Cordova event changes, you'll have to change it in one place
Cons:
you'll have to be careful when inheriting controllers which already have an event handler attached on initialization phase, and if you want your own handler in a child.
Where to place the listeners and the forwarder is up to you and it highly depends on your application structure. If your app allows you could even keep all the logic for the backbutton event in the run block and get rid of it in controllers. Another way to organize it is to specify a single global callback attached to $rootScope for example, which can be overriden inside controllers, if they have different behavior for the back button, not to mess with events.
I am not sure about deviceready event though, it fires once in the very beginning. In my case I was first waiting for the deviceready event to fire and then was manually bootstrapping AngularJS application to provide a sequential load of the app and prevent any conflicts:
document.addEventListener('deviceready', function onDeviceReady() {
angular.element(document).ready(function () {
angular.bootstrap(document.body, ['app']);
});
}, false);
From my point of view the logic of the app and how you bootstrap it should be separated from each other. That's why I've moved listener for backbutton to a run block.

Ionic platform ready event fires twice

Does anyone know how to prevent the event from firing twice? I've tried using a controller scope level boolean variable to see if the event has already fired, but it did not work. It is like the event is firing on 2 separate threads and the variable was always false.
In the code below the $ionicPlatform.ready event is firing twice, but I can't figure out why.I'm using the current version of the Ionic Framework ionic-v1.0.0-beta.13.
angular.module('rsgApp.controllers', [])
.controller('MapCtrl', ['$ionicPlatform',
function ($ionicPlatform) {
var vm = this;
$ionicPlatform.ready(function () {
alert('device is ready');
});
}]);
Thanks TechMa9iac I was able to resolve this problem. In my tab template I had added an 'ng-controller' attribute to my ion-content tag. This is what was causing the $ionicPlatform.ready event to fire twice.

Resources