Best way to toggle Booleans between $rootScope and and a controller - javascript

I have a navbar directive which sits above ng-view. It utilises the $rootScope to trigger events to show buttons in certain views.
I am trying to add a button to the directive template which will switch a boolean in a controller for a particular view. The view shows a period of time and each period has a particular boolean that I want to switch from the directive.
The boolean value is saved in a local storage object which is initialized when each iteration of this particular view is loaded.
First, the value needs to be communicated to the directive so the button can display as being set to true or false. When the switch is toggled, the value of that boolean needs to make its way from the directive, through the $rootScope, to the controller and then be saved in the storage object.
When the view is changed, the whole process needs to repeat. The switch needs to be able to be switched on and off multiple times, obviously.
At present, I am emitting the value from the controller to the $rootScope and then listening for that value in the directive link function.
However, what is the best way to get that $rootScope value BACK into the controller. I tried setting up a $rootScope.$watch in the controller which appeared to work on any single page but when navigating between different time periods, the $rootScope value of the boolean was not resetting properly.
I tried resetting the value in the controller initialization as follows:
$rootScope.booleanValue = false;
but this didn't work.
I have also tried the following:
$scope.$on('$routeChangeSuccess', function (next, current) {
$rootScope.booleanValue = false;
});
but I can't get the whole cycle to work properly. It still seems as though the value of the property in the $rootScope is not resetting from the view before and is then carrying over when an adjacent pay period view is loaded.
I hope this makes sense. I will save you from too much code as I think the basic idea is here.

What you are trying to do is share state from your navbar directive (an isolate scope) and your view's controller. I recommend you use a factory provider service to share that state:
angular.module('myApp').factory('navbarState', function (){
return {started: false}
});
In your navbar directive, inject the service and store the state in that service:
angular.module('myApp').directive('navigationBar', [
'$rootScope',
'navbarState',
//'NavigationStackService',
//'NavigationBarService',
function ($rootScope, navbarState) {
function link(scope, element) {
scope.startEditMode = function(){
console.log("Edit clicked");
navbarState.started=true;
//NavigationBarService.hideNavigationEdit();
//NavigationBarService.showNavigationDone();
};
scope.finishEditMode = function(){
console.log("Done clicked");
navbarState.started=false;
//NavigationBarService.hideNavigationDone();
//NavigationBarService.showNavigationEdit();
};
}
return {
templateUrl: 'templates/navigation-bar.html',
restrict: 'E',
scope: {},
link: link
};
}
]);
In your view controller, retrieve the service, put it on the controller's scope, and use it in your template.
angular.module('myApp').controller('controller2', function(navbarState) {
console.log("view controller2 started");
var vm = this;
vm.navState = navbarState;
vm.message = "hello from ct2";
});
The DEMO on JSFiddle.

Related

Directive Update then run Query to Update Dom on Click

I've looked at more than 10 different directive questions and none have worked for me thus far. I'm trying to have my controller recognize site.selectedUnit has changed which updates selectedChannel in my custom directive. The first time works great, but after that the ng-click does not change the view info. The selectedChannel is registered and stored on my chatList controller, but the http requests are not called again.
If i click on a unit in site.html, the selectedChannel for the unit number changes in the chatList view, so I'm guessing the http requests are not being called again.
How do I add a listener to either the directive or my chatList controller so I can call the http requests again when selectedChannel changes?
Best I can tell from the code you've provided, you need to make a few changes
site.controller
Add a definition for $scope.site otherwise site.selectedUnit will only be available in the context that it is defined in the HTML via ng-click.
$scope.site = {
selectedUnit: null
};
chatList.directive
Remove the isolate scope and inject the selectedChannel property via bindToController so that it will be accessible in the controller.
.directive('chatList', function() {
return {
restrict: 'E',
bindToController: {
selectedChannel: '='
},
templateUrl: 'chatList.html',
controller: 'ChatListController',
controllerAs: 'chatList'
};
})
chatList.controller
Watch for changes to selectedChannel.id to make your $http.get() call
vm.tenants = [];
$scope.$watch(angular.bind(vm.selectedChannel.id, function() {
// make http.get call here
}))
You have other issues as well that are too many to list so here's a working plunker

Angular: how to make a "search" take you to another route and display results?

I have a main page with a nav, and each nav option takes you to another route. It all looks like a single page app, but each "page" has it's own route and controller.
My problem is that I want to put a search box in the navbar. When someone uses the searchbox, I want to take the user to the "search" route and then display the results. I'm having a lot of trouble figuring out these two issues:
Where do I store this "searchbox" logic? E.g. when someone searches, they choose the type of search from a dropdown, then the search query in the inputbox. I have special logic to automatically choose which dropdown value based on the value typed in the inputbox.
How do I redirect to the
"search" route and display the results based on the input from the
previous page?
It's probably clear I'm a newby to Angular. I'm happy to work out the details, but I'm mainly looking to understand how to structure the solution to this problem. Thanks in advance for your help.
What I love about Angular the most is the amount of options you can apply.
Your goal can be reached either by using a service. A service is a singleton class which you can request from controllers. Being a singleton what ever value you store in the service is available to all controllers. You can than either $watch for value change, use $broadcast to notify data change or use $routeParams to send data with route change.
A service is built as follows :
The following assume you have a global module var named 'app'
app.service('myService', function(){
var myValue;
this.getMyValue = function(){
return myValue;
};
this.setMyValue = function(value){
myValue = value;
};
});
Then you request a service from a controller like you request an angular service such as $scope.
app.controller('myController', ['$scope', 'myServce', function($scope, myService){
$scope.myValue = myService.getMyValue();
//Example watch
$scope.$watch('myValue',function(){
//Search criteria changed!!
}, true);
}]);
Angular is terrific..have fun coding
Basically you would want an own state for your search page, so this is where we begin (I expect you to use the ui-router and not Angulars built in router):
.state('search', {
url: "/search",
templateUrl: "pages/search.html",
controller: 'SearchController as ctrl',
params: { searchString: {} }
})
As you can see, I've defined an additional parameter for the search string that is not part of the URL. Of course, if you like, you could change that and move the parameter to the URL instead:
.state('search', {
url: "/search/:searchString",
templateUrl: "pages/search.html",
controller: 'SearchController as ctrl'
})
The actual search input is pretty straight forward as well, because it's only HTML:
<input type="text" ng-model="searchString" on-key-enter="ctrl.goSearch(searchString)">
The function for the state change has to be placed in the controller for the primary template (e.g. the controller of your navigation bar if the search is located there):
var vm = this;
vm.goSearch = goSearch;
function goSearch(searchString) {
$state.go('main.search', { searchString: searchString });
}
Of interest is also the on-key-enter directive that I've added:
angular.module('your.module')
.directive('onKeyEnter', OnKeyEnter);
function OnKeyEnter() {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
scope.$apply(function (){
scope.$eval(attrs.onKeyEnter);
});
event.preventDefault();
}
});
};
}
On pressing the enter-key, it will call the function you supply as attribute value. Of course you could also use a button with ng-click instead of this directive, but I think it simply looks better.
Last, but not least, you need a Search Controller and a HTML template for your search page, which I won't give to you, as it is up to you what you display here. For the controller, you only need to know how you can access the search string:
angular.module('your.module')
.controller('SearchController', SearchController);
SearchController.$inject = ['$scope', '$stateParams'];
function SearchController($scope, $stateParams) {
$scope.searchString = $stateParams.searchString;
/* DO THE SEARCH LOGIC, e.g. database lookup */
}
Hope this helps to find the proper way. :)

How to update directives based on service changes?

I have a directive(parent-directive) containing a slider(mySlider), that on stop event, call an angular $resource service with 2 params and the service return an object.
Directives structure:
<parent-directive>
<div ui-slider="slider.options" ng-model="mySlider" id="my-slider">
<span child-directive-one></span>
<span child-directive-two></span>
<span child-directive-three></span>
<div>
<span child-directive-four></child-directive-four>
</div>
</parent-directive
Whenever the user drag the slider, the service is called with different params and retieve new result, based on it I need to update the child directives.
I have in mind three ways:
using ng-model for all child elements instead directives, binding them on the scope of a controller in parent-directive;
the second one, that I don't know how to do it, is to create a controller in the parent-directive, that send and receive data from the service and share it to child-directives in order to update them.
the last one is to to create a state variable in the service and update it using a controller like to point 1.(see it above) and use a $watch to supervise the variable state and when it's changed then update the child-directives.
How should I proceed?
Please have a look here to see a brief code:
http://jsfiddle.net/v5xL0dg9/2/
Thanks!
ngModel is intended for two way binding, i.e. controls that allow the user to interfere with the value. From the description, it seems they are display-only components. So I would advise against using the ngModel.
Normally child directives require their parent. This allows them to call methods on the parent controller. What you need is the opposite: the parent controller needs to call methods on the children. It can be done: the children call a registerChild() method, and the parent iterates all registered children when it needs to call them. I find this implementation cumbersome.
Services are globals/singletons. I would vote against tying the service implementation to the UI needs.
My advice looks like your implementation of option 3, but with the parent controller holding the data:
1) Place the data you want to share with the child directives in a member variable of the parent controller:
myApp.directive('parentDirective', ['myService', function(myService){
...
controller: function($scope) {
...
this.sharedThing = ...;
}
}]);
The sharedThing can be updated when the service returns new data, or any other time it is necessary.
2) Have the children require the parent (just like your option 2), and watch this property:
myApp.directive('childDirectiveOne', function() {
return {
...
require: 'parentDirective',
link: function(scope, elem, attrs, parentDirective) {
scope.$watch(
function() {
return parentDirective.sharedThing;
},
function(newval) {
// do something with the new value; most probably
// you want to place it in the scope
}
});
}
};
});
Depending on the nature of the data, a deep watch may be required.

Why variable in $scope does not update?

Code in plunker.
I have two controllers. In first controller i have handler for button in my view
$scope.click = function () {
$location.url("/some");
console.log("clicked");
}
In handler i change URL. I also configured my $routeProvider.
var app = angular.module('plunker', []).config( function ($routeProvider) {
$routeProvider.when('/some', {template: " counter is {{n}}</br> <button ng-click='click()'>click to load new url but still with \"loading cntl\"</button>", controller: "loading"})
.when("/second",{controller: "loading"});
});
Here i have two different routes that have the same controller - loading controller
So after my URL was changed to /some new button appears in my view. I have another handler for this button in loading controller.
app.controller("loading", function ($scope,$location) {
$scope.n= $scope.n || 0;
console.log("at the begining n is "+ $scope.n);
$scope.click = function click() {
$scope.n++;
console.log("n after++ is " + $scope.n);
$location.url("/second");
}
});
Here i increment n variable and change URL to /second. In my $routeProvider i indicated that route with this URL must have loading controller as well. After triggering of the button it disappears because /second router have no template. I press button on main view again, my loading controller is executed once more, but the n variable is still 0. Why the value of n is not 1?
I know that my explanation is confusing, but i have the code in plunker
You're instantiating a new controller that has a new scope (and thus a new variable n). You need to keep the iteration data in something more persistant, like a parent scope, service, localStorage, etc (depends what you need the data for).
Here's a working example using $rootScope, just so you can see (you should probably use something other than the $rootScope in your final code): http://plnkr.co/edit/HETROBPwa6VyjX83Eev0?p=preview
I added a simple console.log('scope', $scope); in the controller, so you can see that each time you change the url, a new scope is created.

Share selected select with another controller

I am trying to to share a selected option with another controller (And have it update when I select a new option). Something that would work like the 2-way data binding between controllers.
I've attempted this by setting up a factory like so
.factory("shareObjective", function($scope){
var shareObjective = {};
return {
shareObjective: shareObjective,
};
})
Then I inject this into the controller and bind it to the model of the select like so
$scope.selectModel = shareObjective.shareObjective;
I seem to be having some trouble getting this to work. I Basically just want to share the selected option (it's .name to be precise) with another controller and am struggling to do so. My first step was to get it to share into the factory to begin with, but I seem to be having no luck attempting this. Should I be using something like the $broadcast to keep the stream of information open? Thanks!
Edit - here's a plunkr http://plnkr.co/edit/L5lz4etQ7mUEhf9viNOk?p=preview
Yes, this won't work by default because you use two different scopes thus different ngModels.
Using a service also won't help because even if a click on a select with a ngModel in one scope will trigger a digest loop in that scope, it won't trigger it in the other scope.
As you suggest yourself you need to somehow notify the other scope to update itself, and yes you can do this through events ($broadcast and $on):
Both controllers contain
<select
ng-model="foo"
ng-options="foo for foo in foos"
></select>
And this is the JS:
var foos = [
'foo1',
'foo2',
'foo3'
];
function MyCtrl($scope, $rootScope) {
$scope.foo = foos[0];
$scope.foos = foos;
// detect broadcasts from other controllers and set our value to the one we received
$rootScope.$on('foo-event', function(e, data) {
$scope.foo = data;
});
// detect when foo changes and broadcast it's value
$scope.$watch('foo', function() {
$rootScope.$broadcast('foo-event', $scope.foo);
});
}
myApp.controller('MyCtrl1', ['$scope', '$rootScope', MyCtrl]);
myApp.controller('MyCtrl2', ['$scope', '$rootScope', MyCtrl]);
Here's the fiddle.
Notice that my code does not use a single controller, just a single controller implementation. You can write your own MyCtrl1 and Myctrl2 implementations that both have this code inside.
Also, while it would look like this generates an infinite loop between $watch and $on, it does not. $scope.foo = data; does not trigger $watch,

Categories

Resources