In the following code in angular.js 1.x, I need to create a dashboard dataset which makes a call every few second and update the dom. However it is flickering because of I think $scope.DOMdataArray = []
I have already tried track by $index but didn't help. Is there any way to resolve this issue or write a code in such a way that DOM generated by ng-repeat doesn't flicker?
function someDataInterval () {
$scope.DOMdataArray = []
_.map(urlsArray,function(url) {
$http.get(url).then(function(res) {
// some work on response
$scope.DOMdataArray.push(/*some data for ng-repeat*/)
})
})
}
someDataInterval ()
setInterval(someDataInterval,5000)
Have you tried this ?
function someDataInterval () {
_.map(urlsArray,function(url) {
$http.get(url).then(function(res) {
// some work on response
$scope.DOMdataArray = [];
$scope.DOMdataArray.push(/*some data for ng-repeat*/)
})
})
}
someDataInterval ()
setInterval(someDataInterval,5000)
If this doesn't work you can always use a small loading icon so that flickering is not visible. use ng-show for showing list.
function someDataInterval () {
$scope.loading = true;
_.map(urlsArray,function(url) {
$http.get(url).then(function(res) {
// some work on response
$scope.DOMdataArray = [];
$scope.DOMdataArray.push(/*some data for ng-repeat*/)
$scope.loading = false;
})
})
}
someDataInterval ()
setInterval(someDataInterval,5000)
and HTML :
<h1 ng-show="!loading" ng-repeat="x in DOMdataArray">{{x.name}}</h1>
<img ng-show="loading" src="img/image-loading.gif" />
Related
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
I have applied this sort of line in order to make the component UI updated everytime. But in some other cases it start to refreshing the page event if it should reuse the route.
How can we overcome this issue?
Actually in my application there are three tabs in left panel. In each tab there are some listings clicking on list items opens the content on right panel. But in one of the listing there is a common UI that is getting open on some list item, but the problem is that when we don't apply above sort of code then the UI is not getting updated. But if we apply the code then the UI is updated everytime we click on other list item. But the problem is that when we apply this code it start to refresh the page everytime we click on other list in different tabs also, that should not be the case.
If we apply this code this.router.routeReuseStrategy.shouldReuseRoute = () => false; then how can we revert this functionality under this.router?
To take less risks I'm just reverting it back to what it was once the reload is done:
refresh() {
const prev = this.router.routeReuseStrategy.shouldReuseRoute;
const prevOSN = this.router.onSameUrlNavigation;
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
this.router.onSameUrlNavigation = 'reload';
this.router.navigate([this.router.url]);
setTimeout(() => {
this.router.routeReuseStrategy.shouldReuseRoute = prev;
this.router.onSameUrlNavigation = prevOSN;
}, 0);
}
I have the same issue, I changed that line for this:
// override the route reuse strategy
this.router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
this.router.events.subscribe((evt) => {
if (evt instanceof NavigationEnd) {
// trick the Router into believing it's last link wasn't previously loaded
this.router.navigated = false;
// if you need to scroll back to top, here is the right place
window.scrollTo(0, 0);
}
});
I don't even know if this works well or do the same thing.
private saveRouterStrategyReuseLogic: any;
ngOnInit() {
// Save logic
this.saveRouterStrategyReuseLogic = this.router.routeReuseStrategy.shouldReuseRoute;
this.router.routeReuseStrategy.shouldReuseRoute = (future, curr) => { return false; };
}
ngOnDestroy() {
this.router.routeReuseStrategy.shouldReuseRoute =
this.saveRouterStrategyReuseLogic;
}
I am building a sort of (faux) loader in Angular. Currently, I have this:
const app = angular.module('app', []);
app.controller('loaderCtrl', ($scope, $timeout) => {
let loading = $scope.loading,
loaded = $scope.loaded;
$scope.reset = () => {
$timeout(() => {
loading = false;
loaded = false;
console.log(loaded);
}, 500);
}
});
HTML:
<main ng-app="app">
<div ng-controller="loaderCtrl as loader" >
<div class="loader" ng-class="{ '-loading' : loader.loading === true, '-loaded' : loader.loaded === true }"></div>
<button ng-click="loader.loading = true;">loading</button>
<button ng-click="loader.loaded = true; reset();">loaded</button>
</div>
</main>
CodePen: http://codepen.io/tomekbuszewski/pen/WrXXdp
My problem is, both loading and loaded aren't being set up for my view, so the classes are permanently there. What can I do?
So, this is a problem of scope. Basically when you do this
let loading = $scope.loading,
loaded = $scope.loaded;
You get the "value" of the variables inside Angular scope. Therefore Angular does not know anything about changes made to those
The fix is simple, don't do that, but instead
$scope.reset = () => {
$timeout(() => {
$scope.loading = false;
$scope.loaded = false;
}, 500);
}
Why not using an object and change its content? It is possible to do that as #beaver pointed out, but then you have another problem, you need to trigger the digest cycle yourself via $apply. And somewhere in your code, you might accidentally change the content of the object and it might affect other part of the system
Having said that I do not know Babel and so I worked on the JS compiled version, I noticed that you assigned loader.loading and loader.loaded to variables and then used those "references" in $timeout function.
As in javascript
Primitives are passed by value, Objects are passed by "copy of a
reference"
you have to use $scope.loader.loading and $scope.loader.loaded
app.controller('loaderCtrl', function ($scope, $timeout) {
$scope.loader = {};
var loading = $scope.loader.loading, loaded = $scope.loader.loaded;
$scope.reset = function () {
$timeout(function () {
$scope.loader.loading = false;
$scope.loader.loaded = false;
}, 500);
};
});
Here I forked your CodePen: http://codepen.io/beaver71/pen/wMPprm
When a todo is created,I push it onto this array:
$scope.$on('todo:created',function(event,todo){
$scope.model.todos.push(todo);
});
I am trying to delete a todo using the $scope.$on functionality like this:
//from a child scope for the item
$scope.actions.remove = function remove()
{
TodoService.delete($scope.model.todo);
$scope.$emit('todo:deleted',$scope.model.todo);
};
//from a parent of the scope which has ng-repeat:
$scope.$on('todo:deleted',function(event,todo){
for(var i =0;i<$scope.model.todos.length;i++)
{
if(todo._id === $scope.model.todos[i]._id)
{
console.log(i);
$scope.model.todos.splice(i,1);
break;
}
}
});
I find that this seemingly normal code causes a lot of issues:
1)last item gets deleted correctly
2)when deleting the penultimate item,the last item gets deleted
3)all other items are unresponsive on delete
I find that the UI renders with the correct items deleted on page reload.
I have tried changing the code to:
$scope.$on('todo:deleted',function(event,todo){
$scope.model.todos = $.grep($scope.model.todos, function (todoItem, i) {
if (todoItem._id === todo._id) {
console.log(i);
return false;
} else {
return true;
}
});
});
The entire code can be found here on github
EDIT:
My code uses ng-repeat like this:
<section class="ui three column doubling page grid">
<div class="column" ng-repeat="todo in model.todos track by $index">
<todo-item value="todo"></todo-item>
</div>
</section>
UPDATE:
I have tried to accomplish the delete using this code:
var onItemDeleted = function onItemDeleted(todo){
var todos = $scope.model.todos;
var checkIndex = function checkIndex(t){
return t._id !== todo._id;
};
todos = todos.filter(checkIndex);
//$scope.model.todos = todos;
};
$scope.$on('todo:deleted',function(event,todo){
$scope.$apply(onItemDeleted(todo));
});
var onTodoAdded = function onTodoAdded(todo){
var todos = $scope.model.todos;
todos.push(todo);
};
$scope.$on('todo:created',function(event,todo){
$scope.$apply(onTodoAdded(todo));
});
In both these cases,I get the error:
Error: [$rootScope:inprog] $digest already in progress
http://errors.angularjs.org/1.3.15/$rootScope/inprog?p0=%24digest
at REGEX_STRING_REGEXP (angular.js:66)
at beginPhase (angular.js:14823)
at Scope.$get.Scope.$apply (angular.js:14567)
at app.js:218
at Scope.$get.Scope.$emit (angular.js:14715)
at app.js:264
at processQueue (angular.js:13251)
at angular.js:13267
at Scope.$get.Scope.$eval (angular.js:14469)
at Scope.$get.Scope.$digest (angular.js:14285)
I have tried replacing the data by replacing the data from the service like this:
$scope.$on('todo:deleted',function(event,todo){
var todosPromise = TodoService.get();
todosPromise.then(function(data){
$scope.model.todos = data;
});
});
And I have changed the event code to fire only after the delete operation is completed:
$scope.actions.remove = function remove(id)
{
TodoService.deleteItem($scope.model.todo)
.then(function(){
$scope.$emit('todo:deleted',$scope.model.todo);
})
.catch(function(err){
console.log(err,err.stack);
});
};
I find that the data from the service or upon splicing is obtained correctly but the wrong element is pulled by ng-repeat,is it because I am using track by $index.
I faced some issues with splice and used $grep to fix those issues.
Can you try the below code:
$scope.$on('todo:deleted',function(event, todo) {
$scope.model.todos = $.grep($scope.model.todos, function (todoItem, i) {
if (todoItem._id === todo._id) {
return false;
console.log(i);
} else {
return true;
}
});
});
I have a responsive template that I am trying to use with my Angularjs app. This is also my first Angular app so I know I have many mistakes and re-factoring in my future.
I have read enough about angular that I know DOM manipulations are suppose to go inside a directive.
I have a javascript object responsible for template re-sizes the side menu and basically the outer shell of the template. I moved all of this code into a directive and named it responsive-theme.
First I added all the methods that are being used and then I defined the App object at the bottom. I removed the function bodies to shorten the code.
Basically the object at the bottom is a helper object to use with all the methods.
var directive = angular.module('bac.directive-manager');
directive.directive('responsiveTheme', function() {
return {
restrict: "A",
link: function($scope, element, attrs) {
// IE mode
var isRTL = false;
var isIE8 = false;
var isIE9 = false;
var isIE10 = false;
var sidebarWidth = 225;
var sidebarCollapsedWidth = 35;
var responsiveHandlers = [];
// theme layout color set
var layoutColorCodes = {
};
// last popep popover
var lastPopedPopover;
var handleInit = function() {
};
var handleDesktopTabletContents = function () {
};
var handleSidebarState = function () {
};
var runResponsiveHandlers = function () {
};
var handleResponsive = function () {
};
var handleResponsiveOnInit = function () {
};
var handleResponsiveOnResize = function () {
};
var handleSidebarAndContentHeight = function () {
};
var handleSidebarMenu = function () {
};
var _calculateFixedSidebarViewportHeight = function () {
};
var handleFixedSidebar = function () {
};
var handleFixedSidebarHoverable = function () {
};
var handleSidebarToggler = function () {
};
var handleHorizontalMenu = function () {
};
var handleGoTop = function () {
};
var handlePortletTools = function () {
};
var handleUniform = function () {
};
var handleAccordions = function () {
};
var handleTabs = function () {
};
var handleScrollers = function () {
};
var handleTooltips = function () {
};
var handleDropdowns = function () {
};
var handleModal = function () {
};
var handlePopovers = function () {
};
var handleChoosenSelect = function () {
};
var handleFancybox = function () {
};
var handleTheme = function () {
};
var handleFixInputPlaceholderForIE = function () {
};
var handleFullScreenMode = function() {
};
$scope.App = {
//main function to initiate template pages
init: function () {
//IMPORTANT!!!: Do not modify the core handlers call order.
//core handlers
handleInit();
handleResponsiveOnResize(); // set and handle responsive
handleUniform();
handleScrollers(); // handles slim scrolling contents
handleResponsiveOnInit(); // handler responsive elements on page load
//layout handlers
handleFixedSidebar(); // handles fixed sidebar menu
handleFixedSidebarHoverable(); // handles fixed sidebar on hover effect
handleSidebarMenu(); // handles main menu
handleHorizontalMenu(); // handles horizontal menu
handleSidebarToggler(); // handles sidebar hide/show
handleFixInputPlaceholderForIE(); // fixes/enables html5 placeholder attribute for IE9, IE8
handleGoTop(); //handles scroll to top functionality in the footer
handleTheme(); // handles style customer tool
//ui component handlers
handlePortletTools(); // handles portlet action bar functionality(refresh, configure, toggle, remove)
handleDropdowns(); // handle dropdowns
handleTabs(); // handle tabs
handleTooltips(); // handle bootstrap tooltips
handlePopovers(); // handles bootstrap popovers
handleAccordions(); //handles accordions
handleChoosenSelect(); // handles bootstrap chosen dropdowns
handleModal();
$scope.App.addResponsiveHandler(handleChoosenSelect); // reinitiate chosen dropdown on main content resize. disable this line if you don't really use chosen dropdowns.
handleFullScreenMode(); // handles full screen
},
fixContentHeight: function () {
handleSidebarAndContentHeight();
},
setLastPopedPopover: function (el) {
lastPopedPopover = el;
},
addResponsiveHandler: function (func) {
responsiveHandlers.push(func);
},
// useful function to make equal height for contacts stand side by side
setEqualHeight: function (els) {
var tallestEl = 0;
els = jQuery(els);
els.each(function () {
var currentHeight = $(this).height();
if (currentHeight > tallestEl) {
tallestColumn = currentHeight;
}
});
els.height(tallestEl);
},
// wrapper function to scroll to an element
scrollTo: function (el, offeset) {
pos = el ? el.offset().top : 0;
jQuery('html,body').animate({
scrollTop: pos + (offeset ? offeset : 0)
}, 'slow');
},
scrollTop: function () {
App.scrollTo();
},
// wrapper function to block element(indicate loading)
blockUI: function (ele, centerY) {
var el = jQuery(ele);
el.block({
message: '<img src="./assets/img/ajax-loading.gif" align="">',
centerY: centerY !== undefined ? centerY : true,
css: {
top: '10%',
border: 'none',
padding: '2px',
backgroundColor: 'none'
},
overlayCSS: {
backgroundColor: '#000',
opacity: 0.05,
cursor: 'wait'
}
});
},
// wrapper function to un-block element(finish loading)
unblockUI: function (el) {
jQuery(el).unblock({
onUnblock: function () {
jQuery(el).removeAttr("style");
}
});
},
// initializes uniform elements
initUniform: function (els) {
if (els) {
jQuery(els).each(function () {
if ($(this).parents(".checker").size() === 0) {
$(this).show();
$(this).uniform();
}
});
} else {
handleUniform();
}
},
updateUniform : function(els) {
$.uniform.update(els);
},
// initializes choosen dropdowns
initChosenSelect: function (els) {
$(els).chosen({
allow_single_deselect: true
});
},
initFancybox: function () {
handleFancybox();
},
getActualVal: function (ele) {
var el = jQuery(ele);
if (el.val() === el.attr("placeholder")) {
return "";
}
return el.val();
},
getURLParameter: function (paramName) {
var searchString = window.location.search.substring(1),
i, val, params = searchString.split("&");
for (i = 0; i < params.length; i++) {
val = params[i].split("=");
if (val[0] == paramName) {
return unescape(val[1]);
}
}
return null;
},
// check for device touch support
isTouchDevice: function () {
try {
document.createEvent("TouchEvent");
return true;
} catch (e) {
return false;
}
},
isIE8: function () {
return isIE8;
},
isRTL: function () {
return isRTL;
},
getLayoutColorCode: function (name) {
if (layoutColorCodes[name]) {
return layoutColorCodes[name];
} else {
return '';
}
}
};
}
};
});
Originally the App.init() object method would be called at the bottom of any regular html page, and I have others that do certain things also that would be used on specific pages like Login.init() for the login page and so forth.
I did read that stackoverflow post
"Thinking in AngularJS" if I have a jQuery background? and realize that I am trying to go backwards in a sense, but I want to use this template that I have so I need to retro fit this solution.
I am trying to use this directive on my body tag.
<body ui-view="dashboard-shell" responsive-theme>
<div class="page-container">
<div class="page-sidebar nav-collapse collapse" ng-controller="SidemenuController">
<sidemenu></sidemenu>
</div>
<div class="page-content" ui-view="dashboard">
</div>
</div>
</body>
So here is my problem. This kinda sorta works. I don't get any console errors but when I try to use my side menu which the javascript for it is in the directive it doesn't work until I go inside the console and type App.init(). After that all of the template javascript works. I want to know how to do responsive theme stuff in these directives. I have tried using it both in the compile and link sections. I have tried putting the code in compile and link and calling the $scope.App.init() from a controller and also at the bottom after defining everything. I also tried putting this in jsfiddle but can't show a true example without having the console to call App.init().
My end design would be having some way to switch the pages through ui-router and when a route gets switched it calls the appropriate methods or re-runs the directive or something. The only method that will run on every page is the App.init() method and everything else is really page specific. And technically since this is a single page app the App.init() only needs to run once for the application. I have it tied to a parent template inside ui-router and the pages that will switch all use this shell template. There are some objects that need to access other to call their methods.
Im sorry in advance for maybe a confusing post. I am struggling right now trying to put together some of the ways that you do things from an angular perspective. I will continue to edit the post as I get responses to give further examples.
You said I have read enough about angular that I know DOM manipulations are suppose to go inside a directive but it sounds like you missed the point of a directive. A directive should handle DOM manipulation, yes, but not one directive for the entire page. Each element (or segment) of the page should have its own directive (assuming DOM manip needs to be done on that element) and then the $controller should handle the interactions between those elements and your data (or model).
You've created one gigantic directive and are trying to have it do way too much. Thankfully, you've kinda sorta designed your code in such a way that it shouldn't be too hard to break it up into several directives. Basically, each of your handle functions should be its own directive.
So you'd have something like:
.directive('sidebarMenu', function(){
return {
template: 'path/to/sidebar/partial.html',
link: function(scope, elem, attrs){
// insert the code for your 'handleSidebarMenu()' function here
}
};
})
.directive('horizontalMenu', function(){
return {
template: 'path/to/horizontal/partial.html',
link: function(scope, elem, attrs){
// insert the code for your 'handleHorizontalMenu()' function here
}
};
})
and then your view would look something like:
<body ui-view="dashboard-shell" responsive-theme>
<div class="page-container">
<div class="page-sidebar nav-collapse collapse">
<horizontal-menu></horizontal-menu>
<sidebar-menu></sidebar-menu>
</div>
<div class="page-content" ui-view="dashboard">
</div>
</div>
</body>
And then you don't need a SidebarmenuController because your controller functions shouldn't be handling DOM elements like the sidebar. The controller should just handling the data that you're going to display in your view, and then the view (or .html file) will handle the displaying and manipulation of that data by its use of the directives you've written.
Does that make sense? Just try breaking that huge directive up into many smaller directives that handle specific elements or specific tasks in the DOM.
In my web app while I am updating some data I need to show some loading spinning gif in the web page.
This is my code.
This is my html code
<img src="../../../../Content/images/submit-gif.gif" class="hidegif" data-bind="visible: isWaiting"/>
<button data-bind="click: createNew">Save</button>
In my knockoutjs model I have this
self.isWaiting = ko.observable(false);
self.createNew = function () {
this.isWaiting(true);
$.getJSON("/Admin/Material/GetFolders", function (allData) {
this.isWaiting(true);
var mappedFolders = $.map(allData, function (item) { return new Folder(item); });
self.folders(mappedFolders);
this.isWaiting(false);
}).success(function () { this.isWaiting(false); }).error(function () { }).complete(function () { this.isWaiting(false); }); ;
};
I have property called isWaiting. Before I call the server I am setting it to true. In completion and successive method I am setting it back to false.
So based on that my spinning wheel should appear and disappear.
But this is not working.
Thanks In Advance
this will have another context inside the createNew and callback functions. You should use self instead of this for accessing view model's property:
self.createNew = function () {
self.isWaiting(true);
$.getJSON("/Admin/Material/GetFolders", function (allData) {
self.isWaiting(true);
var mappedFolders = $.map(allData, function (item) { return new Folder(item); });
self.folders(mappedFolders);
self.isWaiting(false);
}).success(function () {
self.isWaiting(false);
}).error(function () {})
.complete(function () {
self.isWaiting(false);
});
};