I have different views each created by a different controller. At a particular time only one of the views is visible.
I want to switch from one view to another view through a function of the controller of the first view and after that I want to call a method of the second view controller.
My problem is how should I call this method in an angular way?
I know the possiblity using $broadcast and $on but that smells a little bit.
The other choice ist to find the scope in the dom and calling the method via scope. But that is even more ugly.
What is the best solution?
You can use services to communicate between controllers. While you could create a generic shared service to have a central point to subscribe to and broadcast events, services are easier to maintain over time.
You can use Angular Routing
Check out the documentation. This is an excerpt from the documentation. You can make links like
Link
For the first route and so on.
phonecatApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/phones', {
templateUrl: 'partials/phone-list.html',
controller: 'PhoneListCtrl'
}).
when('/phones/:phoneId', {
templateUrl: 'partials/phone-detail.html',
controller: 'PhoneDetailCtrl'
}).
otherwise({
redirectTo: '/phones'
});
}]);
Okay it is done and simpler as expected.
The idea is to use a service used in both views (controllers), that contains a 'execution boolean'.
The first view set the boolean to true, the second set a watch on this boolean and therefore is called and can call the desired method.
In the service:
trigger: function(name) { model[name] = true; },
setTriggerWatch: function(scope, name, callback) {
scope.$watch(function value() {
return model[name];
}, function listener(newValue, oldValue) {
if (newValue) {
callback();
}
});
},
In the destination controller:
sessionData.setTriggerWatch($scope, 'createSession', function callCreateSession() {
_createSession();
});
In the source controller:
sessionData.trigger('createSession');
Related
I'm using the native AngularJS router and was wondering if there is a way to assign a controller to a route conditionally. For example, let's say I have three user types:
Guest
User
System Admin
When they come to the home page, I want to be able assign a different controller based on the user type. So I would have three registered controllers: guestHomeCtrl, userHomeCtrl, systemAdminHomeCtrl.
I imagined something like this:
$routeProvider
.when( '/' , {
controller: getHomeCtrl(),
controllerAs: 'homeCtrl'
})
I know I can just pass in the string of the registered controller, but the main issue is being able to find out what type of user is logged in. I have a userService that typically keeps track of that, but it doesn't seem like I can access it from where I set up the routes. Or am I mistaken?
Any direction would help out a lot.
I would suggest using userService with a single controller. Read through the page below, specifically the resolve argument.
https://docs.angularjs.org/api/ngRoute/provider/$routeProvider
This blog post also describes how to use the resolve.
http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx
Try sending the specific function or variable you need to the controller. I used userService.User.userAccountStatus, but it really depends on the setup in your service file.
$routeProvider
.when( '/' , {
controller: HomeCtrl,
controllerAs: 'HomeCtrl',
resolve: {
userService: function(userService) {
return userService.User.userAccountStatus();
}
}
})
I use ngInject for injecting dependencies, but I assume you get the gist of giving services to a controller.
angular
.module('app')
.controller('HomeCtrl', HomeCtrl)
/** #ngInject */
function HomeCtrl($scope, $log, $state, userService) {
}
I can provide further examples if you need them.
I got a directive which has a model passed by an attribute:
use strict;
angular.module('ebs-front')
.directive('ebsIa', function() {
return{
restrict: 'A'.
scope: {
opened: '=ebsIaOpened',
model: '=ebsIaModel',
cb: '&ebsIaCb'
},
controller: function($scope, $uibModal){
console.log('check');
$scope.text = { text: 'test'};
$scope.$watch('opened', function(newValue) {
if(newValue === true){
var modalInstance = $uibModal.open({
controller: 'ImpactAnalyseController',
templateUrl: 'common/directive/ebs-ia-template.html'
});
}
});
}
}
});
In this directive, I need to do some operations and then open a modal window. So for so good, but the thing is, I want the $scope.model to be accessible in ImpactAnalysisController as well.
My assumption was that $scope.test and $scope.model will be available in ImpactAnalysisController automatically, but apparently a isolated scope is created which is only valid for the controller: function part.
What would be a good way to pass the model variable of the scope to the ImpactAnalysisController?! And why isn't it default behaviour in angular?
If I define my directive like below, then the removeFromFilters (in this case) IS available in the directive, so I'm kinda puzzled. Any help would be appreciated...
use strict;
angular.module('ebs-front')
.directive('ebsIa', function() {
return{
restrict: 'A'.
scope: {
opened: '=ebsIaOpened',
model: '=ebsIaModel',
cb: '&ebsIaCb'
},
controller: 'ImpactAnalysisController'
};
)};
There are several ways to share data between controllers in Angular. A couple that come to mind:
1- Use a $rootScope.broadcast('keyName', value) and listen for the value with $scope.on('keyName', function(){...} Use with care, not the best approach most of the time
2- Keep the data not in the controller but in a Service or Factory, and inject that into your controllers (preferable)
What would be a good way to pass the model variable of the scope to the ImpactAnalysisController?!
Depends on what the controller has access to and intends to do with it.
And why isn't it default behaviour in angular?
You're asking the wrong question. You chose an Isolate Scope. Why did you choose an Isolate Scope, if you wanted to inherit properties from its parent?
What may solve your problem:
If you're passing a pure model and expect to have some IO where the user is potentially altering the model I recommend reading and implementing: NgModelController
It will make the model and mechanisms to interact with it available to your directive(s) via an injectable Controller, independent of the type of scope you choose. All you have to do is require 'ngModel' according to $compile documentation.
Fixed with uibmodal's resolve functionality:
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
})
Item is passed from the parent scope to the ModalInstanceCtrl and becomes available in the controller as variable. Exactly was I was looking for!
I'm using ui-router to display 2 ui-views, one within the other. They are organized like this:
.state('itemAbstract', {
url: '/items',
abstract: true,
templateUrl: 'client/views/item.ng.html',
controller: 'moveCtrl',
})
.state('item', {
url: "/:itemId",
parent: "itemsAbstract",
views: {
"otherpage":{
templateUrl: 'client/views/other-page.ng.html',
controller: 'otherPageCtrl'
}
}
})
I run the folloowwing in the otherpage controller when an item is clicked.
$rootScope.$broadcast("somethingClicked",obj)
I try to listen for the event in the item controller:
$scope.$on("somethingClicked",function(a,b){
console.log(a)
console.log(b);
})
Unfortunately, this function never gets called. I tried putting this listener function in the otherpage controller, and it was called correctly when the event happened. For some reason, though, this broadcast isn't getting transferred across scopes. That was the whole reason I was using this, to trigger an action in the parent when something in the parent is clicked. Any ideas on why this is not working?
Here is my controller for the item
angular.module('mm').controller('itemCtrl',
function($scope, $meteor, $rootScope, $state, $stateParams) {
var s = $scope;
s.rs = $rootScope;
$scope.$on("somethingClicked",function(a,b){
console.log("there as a click")
console.log(a)
console.log(b);
})
}
I used Batarang to debug and found that despite this code, $scope is not even registering an event listener. $scope.$$listeners does not have a listener for the somethingClicked event. Very strange, and it doesn't make sense why this isn't working.
Maybe you have independent controllers with no inheritance applied. Inheritance on $scope is declared simply by nesting the controllers on your view. In that case you may use $rootscope to broadcast or listen to event as:
//ctrl1
$rootScope.$broadcast("somethingClicked",obj);
//ctrl2
$rootScope.$on("somethingClicked",function(a,b){
console.log(a)
console.log(b);
});
Take a look at this simple demo as well as an older question on Stack Overflow.
EDITED
Based on your sample code I had no problem at all communicating using $rootscope.
The state declaration use an abstract parent controller and a fetched child controller mapped into the view as:
$stateProvider
.state('test', {
url: '/test',
controller: 'pctrl',
views: {
'main': {
template: '<div ng-controller="pctrl">{{test}}</div>' +
'<div ui-view="childview"></div>'
}
}
})
.state('test.child', {
url: '/test/child',
controller: 'cctrl',
views: {
'childview': {
template: '<div ng-controller="cctrl" />'
}
}
});
Here is a full working demo
Answer found - I had misconfigured my routes file, and had the wrong controller specified for the page I was loading. That's why none of my event listeners registered!
I am trying to have dynamic routing in Angular 1.3. Something similar to what it described here and here. The examples suggest something like this:
$routeProvider.when('/:group/:pagename', {
controller: 'RouteCtrl',
templateUrl: 'uirouter.html'
})
and then the controller will have access to group and pagename through $routeParams. That works
I am trying to make this routing a little more dynamic and have template and controller to be selected dynamically as well:
$routeProvider.when('/:group/:pagename', {
controller: $routeParams.group + 'Ctrl',
templateUrl: $routeParams.pagename + '.html'
})
When I put a breakpoint on when I can see that there is $get property with a function that has $routeParams as one of parameters. But I can't figure out how to retrieve its values.
The project is in very early stage - I can go with ui-router or with ng-router if any of them has this functionality.
For the dynamic templateUrl portion you could try:
$routeProvider.when('/:group/:pagename', {
controller: "SomeCtrl",
templateUrl: function(params){return params.pagename + '.html';}
})
Not sure if the same could be done with the controller however.
Instead of a direct value you can declare a function that will return a templateUrl string, i.e.:
$routeProvider.when('/:group/:pagename', {
controller: $routeParams.group + 'Ctrl',
templateUrl: function (routeParams) {
return routeParams.pagename + '.html';
}
});
I guess the same may be true for controller, but you have to test that one out, as I've never used it for controllers.
That being said, if you have so much dynamic logic in this place, maybe instead of treating this as different controllers, you could encapsulate those views as different directives and the ng-if certain directive depending on $routeParams which will be set in one wrapping controller?
Let's say I have this config:
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'app/partials/index.html',
controller: 'defaultCtrl'
})
.when('/other', {
templateUrl: 'app/partials/other.html',
controller: 'errorCtrl'
})
.otherwise({
templateUrl: 'app/partials/404.html'
});
}
]);
I'm looking for a place to do some basic, common maintenance code before the router calls the route. Say I'd like to clear the console log via console.clear() every time the route is changed. How and where would be the best place in the code to do that?
The $route service raise events like $routeChangeStart which you can use to perform such tasks. You can implement them using the $scope.$on method. Someting like
$scope.$on('$routeChangeStart',function(angularEvent,next,current) {
//do you work here
});
Read the $route documentation to get idea on this and other such events.
Also $routeProvider configuration method when also can take a parameter resolve which actually is used to setup dependencies before the route is resolved. This resolve object map can also be used to achieve what you want to do.