I've a small site that has 3 views, and everytime i change the view, new data is loaded into it (Home, search sombody. Dashboard, a collection of data about them, detail, specific deatils about one item).
I am loading the data like such
<section id="recentSearches" class="frame" data-ng-controller="HomeCtrl as ctrl">
<h1>Recently Searched</h1>
<div data-ng-repeat="name in ctrl.recentSearches | reverse">
<a class="name" href="/#/dashboard/{{name | formatSlug}}" data-ng-bind="name"></a>
</div>
</section>
and just for reference, recentSearches is populated in the controller by a service (this is HomeCtrl) like such:
this.recentSearches = Services.recentSearches.data;
My problem is, every time i switch a view, it doesn't update the previous data in the view, when I reload the page though, it assigns the proper data in the view (recalling the data based on the permalink).
I assume this is happening because the data is not in $scope? When i had the data in scope it updated fine, but i am moving away from storing data in scope completely and this is my last hurtle.
Any help is greatly appreciated and let me know if you need any more info or code. Thanks!
UPDATE: One of my controllers, the other 2 are setup in the same way.
'use strict';
angular.module('myApp.Controller.Home', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/home.html',
pageTitle: 'Home'
});
}])
.controller('HomeCtrl', ['Services', '$rootScope', 'RecentGames', 'Summoners', 'Champions', '$filter',
function(Services, $rootScope, RecentGames, Summoners, Champions, $filter) {
this.slContainer = document.getElementById('summonerLookup');
this.rsContainer = document.getElementById('recentSearches');
this.recentSearches = Services.recentSearches.data;
// Initalize
// -----------------------
this.init = function ( ) {
Services.log('[init][controller] Home');
// Focus on the form
this.slContainer.querySelector('input[name=summonerName]').focus();
// Register Event Listeners
this.events();
// Remove the loading overlay
Services.removeLoading();
};
// Assign Events
// -----------------------
this.events = function ( ) {
// The main form input submit
this.slContainer.addEventListener('submit', this.summonerLookup);
// The recent searches list
this.rsContainer.addEventListener('click', this.loadRecentlySearched.bind(this));
};
// Submit the lookup form
// -----------------------
this.summonerLookup = function ( e, val ) {
if(e){
e.preventDefault();
}
if(!val){
val = $filter('formatSlug')(this.summonerName.value);
}
Summoners.getByName( val ).then(function success(results){ // Grab the summoner
RecentGames.get().then(function success(results){ // Populate the summoners recent games
RecentGames.data = results;
Champions.getUsed();
});
});
};
// Load a recently searched profile
// TODO: load recentsearched from the a tag being clicked, not this.
// -----------------------
this.loadRecentlySearched = function ( e ) {
var el = e.target || e.toElement;
var isButton = el.className.match(/name/g);
// Block event if is not button
if( isButton === null ) { return false; }
// Get summoner information
this.summonerLookup( null, $filter('formatSlug')(el.innerHTML) );
e.preventDefault();
};
return this.init();
}]);
Related
I have created a search box which is being used on two different views, one is for searching jobs and the other is for searching companies. I have made two separate controllers for both and separate services as well.
Here is the html for the searchbox -
<span class="searchButton"><i class="fa fa-search fa-2x"></i></span>
<input ng-change="companies.search()"
ng-model="companies.searchTerm"
ng-keydown="companies.deleteTerm($event)"
type="text" id="search-box"
style="width: 0px; visibility:hidden;"/>
Here is a script i am using for styling it -
<script type="text/javascript">
var toggleVar = true;
$('.searchButton').on('click', function() {
if(toggleVar) {
$('.searchButton').animate({right: '210px'}, 400);
$('#search-box').css("visibility", "visible");
setTimeout(function() {
$('.searchButton').css("color", "#444444");
}, 200);
$('#search-box').animate({ width: 185 }, 400).focus();
toggleVar = false;
}
else {
$('#search-box').animate({ width: 0 }, 400);
$('.searchButton').animate({right: '25px'}, 400);
setTimeout(function() {
$('.searchButton').css("color", "#eeeeee");
}, 300);
toggleVar = true;
}
});
$('#search-box').focusout(function() {
if(!toggleVar) {
$('#search-box').animate({ width: 0 }, 400);
$('.searchButton').animate({right: '25px'}, 400);
setTimeout(function() {
$('.searchButton').css("color", "#eeeeee");
}, 300);
toggleVar = true;
}
});
</script>
Controller -
angular.module('jobSeekerApp')
.controller('CompaniesallCtrl', ['getAllCompanies', function (companiesService) {
var ctrl = this;
var count;
ctrl.pageNumber = 1;
ctrl.searchPageNumber = 1;
ctrl.isSearching = false;
ctrl.searchTerm = "";
// Initial page load
companiesService.getCompanies(ctrl.pageNumber)
.then(function(response) {
ctrl.companiesList = response.data.results;
count = response.data.count;
checkCount();
}, function(error) {
console.log(error);
});
// User clicks next button
ctrl.getNext = function() {
// If search is not being used
if(ctrl.searchTerm === "" && ctrl.isSearching === false) {
ctrl.pageNumber = ctrl.pageNumber + 1;
companiesService.getCompanies(ctrl.pageNumber)
.then(function(response) {
ctrl.companiesList = ctrl.companiesList.concat(response.data.results);
checkCount();
}, function(error) {
console.log(error);
});
}
// If search is being used
else {
ctrl.searchPageNumber = ctrl.searchPageNumber + 1;
companiesService.searchCompany(ctrl.searchPageNumber, ctrl.searchTerm)
.then(function(response) {
ctrl.companiesList = ctrl.companiesList.concat(response.data.results);
checkCount();
}, function(error) {
console.log(error);
});
}
};
// User backspaces to delete search term
ctrl.deleteTerm = function (event) {
if(event.keyCode === 8) {
ctrl.searchTermLen = ctrl.searchTermLen - 1;
}
// If search box is empty
ctrl.isSearching = ctrl.searchTermLen !== 0;
};
// User clicks search button
ctrl.search = function() {
ctrl.searchTermLen = ctrl.searchTerm.length;
// If search box is empty, show normal results
if(ctrl.searchTerm === "" && ctrl.isSearching === false) {
ctrl.pageNumber = 1;
companiesService.getCompanies(ctrl.pageNumber)
.then(function(response) {
ctrl.companiesList = response.data.results;
count = response.data.count;
checkCount();
}, function(error) {
console.log(error);
});
}
// If search box is not empty, search the input
else {
ctrl.isSearching = true;
ctrl.searchPageNumber = 1;
companiesService.searchCompany(ctrl.searchPageNumber, ctrl.searchTerm)
.then(function(response) {
ctrl.companiesList = response.data.results;
count = response.data.count;
checkCount();
}, function(error) {
console.log(error);
});
}
};
// Function to hide and show next button
function checkCount() {
console.log(count);
$(".nextButton").toggle(count > 10);
count = count - 10;
}
}]);
I am trying to make a directive for this, since all this code is being repeated for the both the views. But how do I make the directive interact with different controllers. And how do i make this part ng-change="companies.search()" ng-model="companies.searchTerm" ng-keydown="companies.deleteTerm($event)" not dependent on the controllers.
I am new to angular and am not sure if this is the right approach or should i let the keep the code separate? Please help.
Server-Side search logic makes it simple
If it is possible that your search logic resides on the server and searching jobs or companies could be distinguished by simply setting a query variable in the URL, then it easy. You could use 1 search directive with an attribute to say which module to search and include this in your HTTP request.
Client-Side search logic slightly more angularjs
If you need different client-side logic for each type of search, consider this approach where there is 1 common search directive, plus 1 directive for each customized search.
the common search directive controls view + common search functionality
a search-companies directive that is restrict: 'A' and require: 'search' and performs functions specific to the company search
a search-jobs directive that is also restrict: 'A' and require: 'search' and performs functions specific to the job search
The concept is that the custom search directives will provide their controller/api object to the common search directive. The common search directive handles the view-controller interaction and calls the provided API functions for customized search functionality.
In Code, this could look something like:
angular.module('SearchDemo', [])
.directive('search', function(){
return {
restrict: 'E',
templateUrl: '/templates/search.tpl.html',
controller: ['$scope', function($scope){
$scope.results = [];
this.setSearchAPI = function(searchAPI){
this.api = searchAPI;
};
$scope.doSearch = function(query){
$scope.results.length = 0;
// here we call one of the custom controller functions
if(this.api && angular.isFunction(this.api.getResults)){
var results = this.api.getResults(query);
// append the results onto $scope.results
// without creating a new array
$scope.results.push.apply($scope.results, results);
}
};
}]
};
})
.directive('searchCompanies', function(){
return {
restrict: 'A',
require: ['search', 'searchCompanies'],
link: function(scope, elem, attr, Ctrl){
// here we pass the custom search-companies controller
// to the common search controller
Ctrl[0].setSearchAPI(Ctrl[1]);
},
controller: ['$scope', function($scope){
// you need to design your common search API and
// implement the custom versions of those functions here
// example:
this.getResults = function(query){
// TODO: load the results for company search
};
}]
};
})
.directive('searchJobs', function(){
return {
restrict: 'A',
require: ['search', 'searchJobs'],
link: function(scope, elem, attr, Ctrl){
// here we pass the custom search-jobs controller
// to the common search controller
Ctrl[0].setSearchAPI(Ctrl[1]);
},
controller: ['$scope', function($scope){
// you need to design your common search API and
// implement the custom versions of those functions here
// example:
this.getResults = function(query){
// TODO: load the results for job search
};
}]
};
});
And using it in template would look like:
<search search-companies></search>
and
<search search-jobs></search>
Multiple searches on one directive
This concept could be easily expanded if you need to have one search directive that searches both companies and jobs.
The change would be to turn the search controller's this.api into an array.
angular.module('SearchDemo', [])
.directive('search', function(){
return {
restrict: 'E',
templateUrl: '/templates/search.tpl.html',
controller: ['$scope', function($scope){
$scope.results = [];
// this.api is now an array and can support
// multiple custom search controllers
this.api = [];
this.addSearchAPI = function(searchAPI){
if(this.api.indexOf(searchAPI) == -1){
this.api.push(searchAPI);
}
};
$scope.doSearch = function(query){
$scope.results.length = 0;
// here we call each of the custom controller functions
for(var i=0; i < this.api.length; i++){
var api = this.api[i];
if(angular.isFunction(api.getResults)){
var results = api.getResults(query);
$scope.results.push.apply($scope.results, results);
}
}
};
}]
};
})
.directive('searchCompanies', function(){
return {
restrict: 'A',
require: ['search', 'searchCompanies'],
link: function(scope, elem, attr, Ctrl){
// here we pass the custom search-companies controller
// to the common search controller
Ctrl[0].addSearchAPI(Ctrl[1]);
},
controller: ['$scope', function($scope){
// you need to design your common search API and
// implement the custom versions of those functions here
// example:
this.getResults = function(query){
// TODO: load the results for company search
};
}]
};
})
.directive('searchJobs', function(){
return {
restrict: 'A',
require: ['search', 'searchJobs'],
link: function(scope, elem, attr, Ctrl){
// here we pass the custom search-jobs controller
// to the common search controller
Ctrl[0].addSearchAPI(Ctrl[1]);
},
controller: ['$scope', function($scope){
// you need to design your common search API and
// implement the custom versions of those functions here
// example:
this.getResults = function(query){
// TODO: load the results for job search
};
}]
};
});
And using it in template would look like:
<search search-companies search-jobs></search>
You will have to pass your data source or service to the directive and bind the events from there.
<body ng-app="customSearchDirective">
<div ng-controller="Controller">
<input type="text" placeholder="Search a Company" data-custom-search data-source="companies" />
<input type="text" placeholder="Search for People" data-custom-search data-source="people" />
<hr>
Searching In: {{ searchSource }}
<br/>
Search Result is At: {{ results }}
</div>
</body>
In this sample I am using data-source to pass an array but you can use a service of course.
Then your directive should use the scope attribute to assign what you passed as parameter in source to the scope of the directive.
You will have the input that is using the directive in the elem parameter to bind all the parameters your desire.
(function(angular) {
'use strict';
angular.module('customSearchDirective', [])
.controller('Controller', ['$scope', function($scope) {
$scope.companies = ['Microsoft', 'ID Software', 'Tesla'];
$scope.people = ['Gill Bates', 'Cohn Jarmack', 'Melon Musk'];
$scope.results = [];
$scope.searchSource = [];
}])
.directive('customSearch', [function() {
function link(scope, element, attrs) {
element.on("change", function(e) {
var searchTerm = e.target.value;
scope.$parent.$apply(function() {
scope.$parent.searchSource = scope.source;
scope.$parent.results = scope.source.indexOf(searchTerm);
});
});
}
return {
scope: {
source: '='
},
link: link
};
}]);
})(window.angular);
Using scope.$parent feels a bit hacky I know and limits the use of this directive to be a direct child of the controller but I think it's a good way to get you started.
You can try it out: https://plnkr.co/edit/A3jzjek6hyjK4Btk34Vc?p=preview
Just a couple of notes from the example.
The change event work after you remove focus from the text box (not while you're typing
You will have to search the exact string to get a match
Hope it helps.
Imaging that we have animals table. Each row describes one animal, for example: ID, NAME, TYPE.
Depending on the selected row type, I want show is the sidebar content related to that animal and some user actions.
Content is completely different, it pulls from data from different APIs.
But the sidebar placed always in the same position, same size and styles.
Maybe I'll have common actions for each controller, like -> close sidebar.
If sidebar already opened and user switch to another one, sidebar should change immediately.
How should I design such login with angular ?
I got an idea to define one directive in html for sidebar. And set listener for selected row, after that compile dynamically sidebar directive for selected row, and insert into parent (main) sidebar.
Probably also I need to handle destroy of previous one.
I appreciate if anyone can tell is I'm going the right way... or should I change something ?
function dtSidebarDirective($compile, $mdUtil, $mdSidenav, $log, mxRegistry) {
return {
restrict: 'E',
templateUrl: 'app/components/sidebar/sidebar.html',
controller: function($scope) {
// used to replace sidebar data on the fly without recompile
$scope.refresh = function() { }
$scope.close = function(ev) {
$mdSidenav('right').close()
}
},
scope: true,
link: link
};
function link(scope, element) {
// used to detect switching between the same type of elements
var _activeType;
var _childDirective;
var _childScope;
var _childElement;
var _toggle = $mdUtil.debounce(function() {
$mdSidenav('right')
.toggle()
.then(function() {
scope.isOpen = $mdSidenav('right').isOpen();
$log.debug('toggle right is done');
});
});
var _init = function(type, data) {
// by default open diagram sidebar
switch(type) {
case 'shape':
_childDirective = $compile('<dt-dog-sidebar></dt-dog-sidebar>');
break;
case 'text':
_childDirective = $compile('<dt-cat-sidebar></dt-cat-sidebar>');
break;
default:
_childDirective = $compile('<dt-animal-sidebar></dt-diagram-sidebar>');
}
// initialize child sidebar : element & scope
_activeType = type;
_childScope = scope.$new();
_childScope.data = data;
_childElement = _childDirective(_childScope);
element.find('md-sidenav').append(_childElement);
};
var _isInitialized = function(type) {
var isDefined = angular.isDefined(_childDirective);
return type ? _activeType == type && isDefined : isDefined;
};
var _destroy = function() {
if(_isInitialized()) {
_childScope.$destroy();
_childElement.empty();
_childElement.remove();
}
};
function showSidebar(ev, type, data) {
// lets figure out does we open the same kind of sidebar
if(_isInitialized(type)) {
_childScope.data = data;
_childScope.refresh();
return;
}
// destroy since we gonna replace with new sidebar
_destroy();
_init(type, data);
}
function toggle() {
update();
_toggle();
}
function update(ev) {
// detect which sidebar should be shown now
}
scope.$on('sidebar:toggle', toggle);
scope.$on('sidebar:show', showSidebar);
scope.$on('sidebar:update', update);
}
I manage to get it work with recompiling each time I need to should different sidebar or call refresh of children scope.
I have a little concern here
This comes from a service named BetSlipFactory
removeSlip: function(slip) {
return betSlipSelectionRequest('/betSlip/removeSelection', {
game: slip.game,
pair: slip.pair,
line: slip.line
});
}
Then I have this function in the controller for that service
$scope.removeSlip = function(slip) {
$rootScope.$broadcast('betSlip:removeLines', slip);
BetSlipFactory.removeSlip(slip)
}
Next I have a controller in a different scope named LinesCtrl and I have this function here which calls a couple functions from the service BetSlipFactory which is like a kind of toggle function
$rootScope.$on('betSlip:removeLines', function(event, slip) {
if (slip) {
BetSlipFactory.remove(line, row, type);
};
});
$scope.addLineToBetSlip = function(line, row, type) {
var spreadSelected = (row.spreadSelected && type === 'spread'),
totalSelected = (row.totalSelected && type === 'total'),
moneyLineSelected = (row.moneyLineSelected && type === 'moneyline');
if (spreadSelected || totalSelected || moneyLineSelected) {
BetSlipFactory.remove(line, row, type);
}else {
BetSlipFactory.add(line, row, type);
}
};
And then the HTML:
<button ng-click="removeSlip(slip)"></button>
And:
<td ng-class="!row.moneyLineSelected ? 'lines-hover' : 'line-selected'">
<a ng-click="addLineToBetSlip(line, row, 'moneyline')">
<span ng-hide="row.noMoneyLine">{{:: row.moneyLine}}</span>
</a>
</td>
What I need: combine the scopes, when the function $scope.removeSlip(slip) is call, also I need to call $scope.addLineToBetSlip(line, row, type) and then that function should call BetSlipFactory.remove(line, row, type); as it is within that if statement.
When I call $scope.removeSlip(slip) I need to kill slip parameter, within the scope of BetSlipFactory everything works great.
I recorded a video for you to see what I am talking about, let me explain the video a little bit.
In the first 2 tries you might see that I am able to select and deselect and everything works great, but in the 3rd and 4th try, you see that I select a line, and then I go a call and removeSlip(slip) when I play the X on the right, and in order to deselect the line on the left I have to do it manually.
So I started a fiddle showing this process dumbed way down compared to the plnkr you started after. Here I am using two separate controllers and a service (factory) to manage the data. This can be done without using $rootScope or $broadcast. Hopefully you can take what I have done here and integrate it into all that code you posted on plnkr. Below you can see it is quite a simple process
the jsfiddle
HTML:
<div ng-app="TestApp">
<div id="colLeft" ng-controller="LeftController">
<div ng-repeat="bet in possibleBets">
<button ng-class="!bet.moneyLineSelected ? 'lines-hover' : 'line-selected'" ng-click="addLineToBetSlip(bet)">{{bet.name}}</button>
</div>
</div>
<div id="colRight" ng-controller="RightController">
Your Bets:<br>
<div ng-repeat="bet in bets">
Active bet: {{bet.name}} - <button ng-click="removeLineFromBetSlip(bet)">×</button>
</div>
</div>
</div>
CSS:
.lines-hover {
}
.line-selected {
background:yellow;
}
#colLeft {
width:65%;
background:#f00;
float:left;
}
#colRight {
width:35%;
background:gray;
float:left;
}
and finally the JS
var app = angular.module('TestApp',[]);
app.controller('LeftController', function($scope, BetSlipFactory)
{
// this data is the data from your DB
$scope.possibleBets = [
{name:'Bet 1',moneyLineSelected:false},
{name:'Bet 2',moneyLineSelected:false},
{name:'Bet 3',moneyLineSelected:false}
];
// now that I think about it, addLineToBetSlip is not a good name
// since it actually toggles the bet
$scope.addLineToBetSlip = function(bet)
{
bet.moneyLineSelected = !bet.moneyLineSelected; // toggle the moneyLineSelected boolean
(bet.moneyLineSelected) ? BetSlipFactory.add(bet) : BetSlipFactory.remove(bet); // add or remove the bet
};
});
app.controller('RightController', function($scope, BetSlipFactory)
{
$scope.bets = BetSlipFactory.getAllBets(); // link to all the active bets
// remove the bet from the factory
$scope.removeLineFromBetSlip = function(bet)
{
bet.moneyLineSelected = false;
BetSlipFactory.remove(bet);
};
});
app.service('BetSlipFactory', function()
{
//a place to keep active bets
var theBets = [];
return {
add: function(bet)
{
// actually add the bet to this local array
theBets.push(bet);
},
remove: function(bet)
{
// you should do error checking of the index before removing it
var index = theBets.indexOf(bet);
theBets.splice(index,1);
},
getAllBets: function()
{
//simply return all active bets
return theBets;
}
}
});
function log(msg)
{
console.log(msg);
}
i'm building an app with angularjs, i have implemented infinite scrolling technique because i have a lot of items to show, so it's a better experience than pagination, but the bad thing that i'm having it's that if the user clicks on item it goes to item page, but when he wants to go back he will be on the top and he should keep scrolling. that's what i want to accomplish if he hits back button he could back to his position where he were !!
Listing Items:
<div class="container" id="infinit-container" ng-controller="ArticlesController">
<div id="fixed" when-scrolled="LoadMore()">
<div ng-repeat="article in Articles">
<article-post article="article"></article-post>
</div>
</div>
</div>
here is when-scrolled directive
app.directive('whenScrolled', function () {
return function (scope, element, attrs) {
$('#fixed').height($(window).height());
var div = element[0];
element.bind('scroll', function () {
if (div.scrollTop + div.offsetHeight >= div.scrollHeight) {
scope.$apply(attrs.whenScrolled);
}
})
}
})
thats the controller
app.controller('ArticlesController', function ($scope, UserService) {
$scope.Articles = [];
var page = 0;
$scope.LoadMore = function () {
UserService.Articles(page)
.success(function (data) {
$scope.Articles.push.apply($scope.Articles, data);
});
page++;
};
$scope.LoadMore();
});
im using page number, save page number somewhere (i prefer sessionStorage) when going to see the item detail , when user is comming back to list, read page number and load the page.
it is the simple code for main page controller (list)
app.controller('ArticlesController', function($scope, UserService) {
$scope.Articles = [];
var page = 0;
$scope.LoadMore = function() {
UserService.Articles(page)
.success(function(data) {
$scope.Articles.push.apply($scope.Articles, data);
});
page++;
}
$scope.LoadArticle = function(articleId) {
sessionStorage.setItem("pageNumber", page);
/// change path to somewhere you want show your article
};
//it will load the page you coming back from
if (sessionStorage["pageNumber"]) {
page = parseInt(sessionStorage["pageNumber"]);
}
LoadMore();
});
because of using sessionStorage , it will deleted if user close the browser or page as expected.
I'm trying to pass in a $scope that I want to change the value on.
These are two switch button on the same page that.
View
<div class="input">
<switch state="false" toggle="user.emailNotification">
<flip></flip>
</switch>
</div>
<div ng-click="saveNotifySettings()" class="button fill primary">Vista</div>
Controller
app.controller('notifySettingCtrl', function($scope, Users){
Users.get().$promise.then(function(data) {
$scope.user = data;
console.log($scope.user.emailNotification);
});
$scope.saveNotifySettings = function() {
console.log("PUT the new value for the switch");
};
});
When I press the button the state changes from false to true
First I want to init the state with the existing value from $scope.user.emailNotification and then change it and pass the changes to the controller.
The beginning of the my directive.
switch directive
(function() {
define(['angular', 'app', 'underscore'], function(angular, app, _) {
app.directive('switch', function() {
return {
restrict: 'E',
scope: {
value: '&toggle',
},
link: function(scope, element) {
var x = scope.value();
element.bind('mouseenter', function() {
console.log(x);
});
var $element = angular.element(element),
uniqueId = _.uniqueId('switch-'),
state = $element.attr('state');
state = typeof state === 'undefined' ? false : state;
$element.data('uniqueId',uniqueId)
.attr('state',state)
.attr('alive',true);
$element.on('click.'+uniqueId,function(){
if (state === true) {
$(this).attr('state',false);
state = false;
} else {
$(this).attr('state',true);
state = true;
}
});
}
};
});
});
}).call(this);
I'm very new at creating directives, so any help is well appreciated.
I have spend way to much time at this and it getting frustrating :/
Update:
I have created http://jsfiddle.net/HuLn4/. I have taken the pointers from you and refactored.
TLDR: I'm trying to create directive by sending in the model that I want to change in this case user.emailNotification and when the element is clicked on it changes the value from true/false and false/true and stores it back to the controllers $scope.user so it can be PUT to server and the state attribute is only to tell the look on the switch and for the initialize on the button ( on / off ).