Is it possible to share scope behavior from one of my controllers higher up in my app hierarchy so that it's able to manage data from an unrelated/uninherited scope as a sort of abstract and separate 'remote control'?
This is how I have things setup in psudo-angular:
//Looking to share the ManagedScope1 and ManagedScope2 "changeChannel()" behavior with this controller
<RemoteControlCtrl>
<ng-click="managedScope1.changeChannel()"></ng-click>
<ng-click="managedScope2.changeChannel()"></ng-click>
</RemoteControlCtrl>
//ManagedScopes inherit ChangeChannelCtrl scope behaviors
<ChannelChangeCtrl with $scope.changeChannel() method>
<ManagedScope1></ManagedScope1>
<ManagedScope2></ManagedScope2>
</ChannelChangeCtrl>
The $scope.changeChannel() method is inherited in both managed scopes, and can act on their own data accordingly.
You need a ChannelService....
.service('ChannelService', function () {
return {
changeChannel: function (scopeData, callback) {
//change the channel
if (angular.isFunction(callback)) {
callback();
}
}
};
});
Usage:
.controller('MyController', ['$scope', 'ChannelService', function ($scope, ChannelService) {
$scope.dataForChangingChannel = {};
$scope.changeChannel = function () {
//do UI stuff here
ChannelService.changeChannel($scope.dataForChangingChannel, function () {
//or UI stuff here, after the channel has been changed
});
}
}]);
It would depends on what kind of component that generated the scope.
If it is a completely unrelated scope, you should use $broadcast. You can require $rootScope as dependancies in remote controller and $rootScope.$broadcast('eventName', someData). In your channel controller:
$scope.$on('eventName', function(event, data) {
// Do something here
})
Another good idea would be using a service, but that would still be hard to call method on another scope. I would say event broadcasting is a nice approach for your problem.
Related
I'm trying to stop all event listeners while scope is destroyed.
I get this error:
TypeError: vm.$on is not a function;
Neither vm.on(..) works
angular.module('app.layout')
.controller('DashboardController', DashboardController);
DashboardController.$inject = ['$interval','dataservice'];
function DashboardController($interval, dataservice) {
var vm = this;
vm.name = "DashboardController";
console.log('Init Dashboard Controller');
initEvents();
/*
...
*/
/////////////////////////////
function initEvents() {
vm.$on('$destroy', function() {
vm.stop();
console.log('DashboardController scope destroyed.');
})
}
The problem is that vm doesn't have the $on(... declared, you must use $scope instead. Inject it on your controller and declare like $scope.$on.
When using controllerAs syntax, this very often missunderstood that you shouldn't use $scope at all. However, the recomendation is to avoid using $scope for certain activities not abolish it from your controller. Scope always will exists, it's an internal of your controller, just don't use it like a view model, but you can use it anyways for such tasks like, listen to events, broadcast, emmit, etc.
Try something like (after you've injected $scope on your dependencies):
$scope.$on('$destroy', function() {
vm.stop();
console.log('DashboardController scope destroyed.');
})
Before this is marked as duplicate I've read quite of few similar questions, but all the answers I've found seem to use $scope, and after reading the documentation I'm not really sure I understand $scope, or why I'd use it in this situation.
I found this tutorial which describes how to do what I'm trying to do.
However, it's using an array of data. I just need one solid variable. In addition, I don't know why he's declaring an additional object to the factory service he creates; why not just use the factory as the object?
I was thinking I could do something like this, but I'm not sure if it will work or not.
Creating my factory/service:
var demoModule = angular.module("demoModule", []);
demoModule.factory("demoService", function() {
var demoSharedVariable = null;
return demoSharedVariable;
});
Accessing the shared variable in each controller:
var demoControllerOne = demoModule.controller("demoContollerOne", function(demoSharedVariable) {
this.oneFunction = function(oneInput){
demoSharedVariable = oneInput;
};
});
var demoControllerTwo = demoModule.controller("demoContollerTwo", function(demoSharedVariable) {
this.twoFunction = function(twoInput){
demoSharedVariable = twoInput;
};
});
Will this method produced the shared variable I'm after?
You need to inject the service in order to use it, then access the service variable.
demoModule.controller("demoContollerOne", function($scope, demoService) {
$scope.oneFunction = function(){
demoService.demoSharedVariable = $scope.oneInput;
};
});
demoModule.controller("demoContollerTwo", function($scope, demoService) {
$scope.twoFunction = function(){
demoService.demoSharedVariable = $scope.twoInput;
};
});
If you are using controllerAs, you rarely (or shouldn't) need to inject and use $scope. As controllerAs is a relatively newer feature, back then we have no choice but to use $scope, so it is not strange to find example with $scope.
Edit: If you are not using controllerAs (like in this example) you would need $scope to expose functions or variables to the view.
There are several place that are not correct I've found while fiddling with it, I'll edit the code. I don't know how to showcase the effect without using advanced concept like $watch, please provide your own fiddle if you don't understand.
Jsbin
One important thing is if you want to use angular, you have to understand the knowledge of scope.
Since neither you factory or controller is correct, i write a simple example for you to help you understand the service:
detail implementation in this plnkr:
service:
angular.module('myApp').service('MyService', [function() {
var yourSharedVariable; // Your shared variable
//Provide the setter and getter methods
this.setSharedVariable = function (newVal) {
yourSharedVariable = newVal;
};
this.getSharedVariable = function () {
return yourSharedVariable;
};
}
]);
controller:
myApp.controller('Ctrl2', ['$scope', 'MyService', '$window', function($scope, MyService, $window) {//inject MyService into the controller
$scope.setShared = function(val) {
MyService.setSharedVariable(val);
};
$scope.getShared = function() {
return MyService.getSharedVariable();
};
$scope.alertSharedVariable = function () {
$window.alert(MyService.getSharedVariable());
};
}]);
I'm developing a Cordova/PhoneGap app, and I'm using the $cordovaPush plugin (wrapped for PushPlugin) to handle push notifications.
The code looks something like this:
var androidConfig = {
"senderID" : "mysenderID",
"ecb" : "onNotification"
}
$cordovaPush.register(androidConfig).then(function(result) {
console.log('Cordova Push Reg Success');
console.log(result);
}, function(error) {
console.log('Cordova push reg error');
console.log(error);
});
The "ecb" function must be defined with window scope, ie:
window.onNotification = function onNotification(e)...
This function handles incoming events. I'd obviously like to handle incoming events in my angular code - how can I integrate the two so that my onNotification function can access my scope/rootScope variables?
Usually, you'll wrap your 3rd party library in a service or a factory, but in the spirit of answering your particular scenario...
Here's one possibility:
angular.module('myApp').
controller('myController', function($scope, $window) {
$window.onNotification = function() {
$scope.apply(function() {
$scope.myVar = ...updates...
});
};
});
A couple of things to notice:
Try to use $window, not window. It's a good habit to get into as it will help you with testability down the line. Because of the internals of Cordova, you might actually need to use window, but I doubt it.
The function that does all of the work is buried inside of $scope.apply. If you forget to do this, then any variables you update will not be reflected in the view until the digest cycle runs again (if ever).
Although I put my example in a controller, you might put yours inside of a handler. If its an angular handler (ng-click, for example), you might think that because the ng-click has an implicit $apply wrapping the callback, your onNotification function is not called at that time, so you still need to do the $apply, as above.
...seriously... don't forget the apply. :-) When I'm debugging people's code, it's the number one reason why external libraries are not working. We all get bit at least once by this.
Define a kind of a mail controller in body and inside that controller use the $window service.
HTML:
<body ng-controller="MainController">
<!-- other markup .-->
</body>
JS:
yourApp.controller("BaseController", ["$scope", "$window", function($scope, $window) {
$window.onNotification = function(e) {
// Use $scope or any Angular stuff
}
}]);
I need to scroll to a specific anchor tag on page reload. I tried using $anchorScroll but it evaluates $location.hash(), which is not what I needed.
I wrote a custom provider based on the source code of $anchorScrollProvider. In it, it adds a value to the rootScope's $watch list, and calls an $evalAsync on change.
Provider:
zlc.provider('scroll', function() {
this.$get = ['$window', '$rootScope', function($window, $rootScope) {
var document = $window.document;
var elm;
function scroll() {
elm = document.getElementById($rootScope.trendHistory.id);
if (elm) elm.scrollIntoView();
}
$rootScope.$watch(function scrollWatch() {return $rootScope.trendHistory.id;},
function scrollWatchAction() {
if ($rootScope.trendHistory.id) $rootScope.$eval(scroll);
});
return scroll;
}];
});
Now, when I try to call the scroll provider in my controller, I must force a digest with $scope.$apply() before the call to scroll():
Controller:
//inside function called on reload
$scope.apply();
scroll();
Why must I call $scope.$apply()? Why isn't the scroll function evaluating in the Angular context when called inside the current scope? Thank you for your help!
I'm not sure what your thinking is behind using $rootScope.$eval(scroll) - since the scroll() function is already executing in a context where it has direct access to the $rootScope.
If I understand correctly, you want to be able to scroll to a particular element as denoted by an id which is stored in $rootScope.trendHistory.id.
When that id is changed, you want to scroll to that element (if it exists on the page).
Assuming this is a correct interpretation of what you are trying to achieve, here is how I might go about implementing it:
app.service('scrollService', function($rootScope) {
$rootScope.trendHistory = {};
$rootScope.$watch('trendHistory.id', function(val) {
if (val) {
elm = document.getElementById($rootScope.trendHistory.id);
if (elm) elm.scrollIntoView();
}
});
this.scrollTo = function(linkId) {
$rootScope.trendHistory.id = linkId;
}
});
This is a service (like your provider, but using the simpler "service" approach) which will set up a $watch on the $rootScope, looking for changes to $rootScope.trendHistory.id. When a change is detected, it scrolls to the element indicated if it exists - that bit is taken directly from your code.
So to use this in a controller, you'd inject the scrollService and then call its scrollTo() method with the ID as an argument. Example:
app.controller('AppController', function($scope, scrollService) {
scrollService.scrollTo('some_id');
});
In your question, you mention this needing to occur on reload, so you'd just put the call into your reload handler. You could also just directly modify the value of $rootScope.trendHistory.id from anywhere in the app and it would also attempt to scroll.
Here is a demo illustrating the basic approach: http://plnkr.co/edit/cJpHoSemj2Z9muCQVKmj?p=preview
Hope that helps, and apologies if I misunderstood your requirements.
I'd like to have a "Global function" called the first time I launch my AngularJS application, or every time I refresh the page.
This function will call my server with $http.get() to get global information necessary to use my application. I need to access $rootScope in this function. After that, and only after this request finished, I'm using app.config and $routeProvider.when() to load the good controller.
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/',
{
/**/
});
}]);
I don't want the application do something before this action is finished. So I guess I have to use a "resolve", but I don't really know how to use it.
Any idea?
Thanks!
It's not the best way to solve your given problem, but here is a proposed solution for your question.
Anything inside run(...) will be run on initialization.
angular.module('fooApp').run(['$http', '$rootScope' function($http, $rootScope) {
$http.get(...).success(function(response) {
$rootScope.somedata = response;
});
$rootScope.globalFn = function() {
alert('This function is available in all scopes, and views');
}
}]);
Now an alert can be triggered in all your views, using ng-click="globalFn()".
Be aware that directives using a new isolate scope will not have access to this data if not explicitly inherited: $scope.inheritedGlobalFn = $rootScope.globalFn
As a first step for your solution, I think that you could monitor the $routeChangeStart event that is triggered before every route change (or page refresh in your case).
var app = angular.module('myApp').run(['$rootScope', function($rootScope) {
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (!$rootScope.myBooleanProperty)) {
$location.path('/');
}
else {
$location.path('/page');
}
});
});
You should have a look at this article about Authentification in a Single Page App. I think you could work something similar.
Please consider this answer:
https://stackoverflow.com/a/27050497/1056679
I've tried to collect all possible methods of resolving dependencies in global scope before actual controllers are executed.