angularjs <timer /> won't update - angularjs

I have this angularjs controller
angular.module('dashboardApp', ['timer']);
function timingController($scope) {
$scope.timerRunning = false;
$scope.startTimer = function () {
$scope.$broadcast('timer-start');
$scope.timerRunning = true;
};
$scope.stopTimer = function () {
$scope.$broadcast('timer-stop');
$scope.timerRunning = false;
};
$scope.resumeTimer = function () {
$scope.$broadcast('timer-resume');
$scope.timerRunning = true;
};
}
timingController.$inject = ['$scope'];
and this HTML
<div class="row" ng-controller="timingController">
<div class="col-md-12">
<p>
<timer> minutes, seconds.</timer><br />
<button type="button" ng-click="startTimer()" ng-show="!timerRunning" ng-disabled="timerRunning" class="btn btn-success btn-lg btn-block" id="start-timer">Start Timer</button>
<button type="button" ng-click="resumeTimer()" ng-show="timerRunning" ng-disabled="!timerRunning" class="btn btn-success btn-lg btn-block" id="resume-timer">Resume Timer</button>
<button type="button" ng-click="stopTimer()" ng-show="timerRunning" ng-disabled="!timerRunning" class="btn btn-danger btn-lg btn-block" id="stop-timer">Stop Timer</button>
<button type="button" class="btn btn-danger btn-lg btn-block" id="reset-timer" style="display:none;">Reset Timer</button>
</p>
</div>
</div>
The controller is detected, methods are called and i have inserted the timer js directive.. But The values doen't seem to update (broadcast doesn't seem to work). Do you see any problem with this code?
I haven't got any online hosting to host the timer.js script, so my jsfiddle here has problems loading :(

Just change <timer> minutes, seconds.</timer> to <timer>{{minutes}} minutes, {{seconds}} seconds.</timer>.
See the code snippet below. (I embedded the code for the timer directive only so that you can test it here.)
angular.module('dashboardApp', ['timer']);
function timingController($scope) {
$scope.timerRunning = false;
$scope.startTimer = function () {
$scope.$broadcast('timer-start');
$scope.timerRunning = true;
};
$scope.stopTimer = function () {
$scope.$broadcast('timer-stop');
$scope.timerRunning = false;
};
$scope.resumeTimer = function () {
$scope.$broadcast('timer-resume');
$scope.timerRunning = true;
};
}
timingController.$inject = ['$scope'];
/**
* angular-timer - v1.1.6 - 2014-07-01 7:37 AM
* https://github.com/siddii/angular-timer
*
* Copyright (c) 2014 Siddique Hameed
* Licensed MIT <https://github.com/siddii/angular-timer/blob/master/LICENSE.txt>
*/
var timerModule = angular.module('timer', [])
.directive('timer', ['$compile', function ($compile) {
return {
restrict: 'EAC',
replace: false,
scope: {
interval: '=interval',
startTimeAttr: '=startTime',
endTimeAttr: '=endTime',
countdownattr: '=countdown',
finishCallback: '&finishCallback',
autoStart: '&autoStart',
maxTimeUnit: '='
},
controller: ['$scope', '$element', '$attrs', '$timeout', function ($scope, $element, $attrs, $timeout) {
// Checking for trim function since IE8 doesn't have it
// If not a function, create tirm with RegEx to mimic native trim
if (typeof String.prototype.trim !== 'function') {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
//angular 1.2 doesn't support attributes ending in "-start", so we're
//supporting both "autostart" and "auto-start" as a solution for
//backward and forward compatibility.
$scope.autoStart = $attrs.autoStart || $attrs.autostart;
if ($element.html().trim().length === 0) {
$element.append($compile('<span>{{millis}}</span>')($scope));
} else {
$element.append($compile($element.contents())($scope));
}
$scope.startTime = null;
$scope.endTime = null;
$scope.timeoutId = null;
$scope.countdown = $scope.countdownattr && parseInt($scope.countdownattr, 10) >= 0 ? parseInt($scope.countdownattr, 10) : undefined;
$scope.isRunning = false;
$scope.$on('timer-start', function () {
$scope.start();
});
$scope.$on('timer-resume', function () {
$scope.resume();
});
$scope.$on('timer-stop', function () {
$scope.stop();
});
$scope.$on('timer-clear', function () {
$scope.clear();
});
$scope.$on('timer-set-countdown', function (e, countdown) {
$scope.countdown = countdown;
});
function resetTimeout() {
if ($scope.timeoutId) {
clearTimeout($scope.timeoutId);
}
}
$scope.start = $element[0].start = function () {
$scope.startTime = $scope.startTimeAttr ? new Date($scope.startTimeAttr) : new Date();
$scope.endTime = $scope.endTimeAttr ? new Date($scope.endTimeAttr) : null;
if (!$scope.countdown) {
$scope.countdown = $scope.countdownattr && parseInt($scope.countdownattr, 10) > 0 ? parseInt($scope.countdownattr, 10) : undefined;
}
resetTimeout();
tick();
$scope.isRunning = true;
};
$scope.resume = $element[0].resume = function () {
resetTimeout();
if ($scope.countdownattr) {
$scope.countdown += 1;
}
$scope.startTime = new Date() - ($scope.stoppedTime - $scope.startTime);
tick();
$scope.isRunning = true;
};
$scope.stop = $scope.pause = $element[0].stop = $element[0].pause = function () {
var timeoutId = $scope.timeoutId;
$scope.clear();
$scope.$emit('timer-stopped', {timeoutId: timeoutId, millis: $scope.millis, seconds: $scope.seconds, minutes: $scope.minutes, hours: $scope.hours, days: $scope.days});
};
$scope.clear = $element[0].clear = function () {
// same as stop but without the event being triggered
$scope.stoppedTime = new Date();
resetTimeout();
$scope.timeoutId = null;
$scope.isRunning = false;
};
$element.bind('$destroy', function () {
resetTimeout();
$scope.isRunning = false;
});
function calculateTimeUnits() {
// compute time values based on maxTimeUnit specification
if (!$scope.maxTimeUnit || $scope.maxTimeUnit === 'day') {
$scope.seconds = Math.floor(($scope.millis / 1000) % 60);
$scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
$scope.hours = Math.floor((($scope.millis / (3600000)) % 24));
$scope.days = Math.floor((($scope.millis / (3600000)) / 24));
$scope.months = 0;
$scope.years = 0;
} else if ($scope.maxTimeUnit === 'second') {
$scope.seconds = Math.floor($scope.millis / 1000);
$scope.minutes = 0;
$scope.hours = 0;
$scope.days = 0;
$scope.months = 0;
$scope.years = 0;
} else if ($scope.maxTimeUnit === 'minute') {
$scope.seconds = Math.floor(($scope.millis / 1000) % 60);
$scope.minutes = Math.floor($scope.millis / 60000);
$scope.hours = 0;
$scope.days = 0;
$scope.months = 0;
$scope.years = 0;
} else if ($scope.maxTimeUnit === 'hour') {
$scope.seconds = Math.floor(($scope.millis / 1000) % 60);
$scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
$scope.hours = Math.floor($scope.millis / 3600000);
$scope.days = 0;
$scope.months = 0;
$scope.years = 0;
} else if ($scope.maxTimeUnit === 'month') {
$scope.seconds = Math.floor(($scope.millis / 1000) % 60);
$scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
$scope.hours = Math.floor((($scope.millis / (3600000)) % 24));
$scope.days = Math.floor((($scope.millis / (3600000)) / 24) % 30);
$scope.months = Math.floor((($scope.millis / (3600000)) / 24) / 30);
$scope.years = 0;
} else if ($scope.maxTimeUnit === 'year') {
$scope.seconds = Math.floor(($scope.millis / 1000) % 60);
$scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
$scope.hours = Math.floor((($scope.millis / (3600000)) % 24));
$scope.days = Math.floor((($scope.millis / (3600000)) / 24) % 30);
$scope.months = Math.floor((($scope.millis / (3600000)) / 24 / 30) % 12);
$scope.years = Math.floor(($scope.millis / (3600000)) / 24 / 365);
}
// plural - singular unit decision
$scope.secondsS = $scope.seconds == 1 ? '' : 's';
$scope.minutesS = $scope.minutes == 1 ? '' : 's';
$scope.hoursS = $scope.hours == 1 ? '' : 's';
$scope.daysS = $scope.days == 1 ? '' : 's';
$scope.monthsS = $scope.months == 1 ? '' : 's';
$scope.yearsS = $scope.years == 1 ? '' : 's';
//add leading zero if number is smaller than 10
$scope.sseconds = $scope.seconds < 10 ? '0' + $scope.seconds : $scope.seconds;
$scope.mminutes = $scope.minutes < 10 ? '0' + $scope.minutes : $scope.minutes;
$scope.hhours = $scope.hours < 10 ? '0' + $scope.hours : $scope.hours;
$scope.ddays = $scope.days < 10 ? '0' + $scope.days : $scope.days;
$scope.mmonths = $scope.months < 10 ? '0' + $scope.months : $scope.months;
$scope.yyears = $scope.years < 10 ? '0' + $scope.years : $scope.years;
}
//determine initial values of time units and add AddSeconds functionality
if ($scope.countdownattr) {
$scope.millis = $scope.countdownattr * 1000;
$scope.addCDSeconds = $element[0].addCDSeconds = function (extraSeconds) {
$scope.countdown += extraSeconds;
$scope.$digest();
if (!$scope.isRunning) {
$scope.start();
}
};
$scope.$on('timer-add-cd-seconds', function (e, extraSeconds) {
$timeout(function () {
$scope.addCDSeconds(extraSeconds);
});
});
$scope.$on('timer-set-countdown-seconds', function (e, countdownSeconds) {
if (!$scope.isRunning) {
$scope.clear();
}
$scope.countdown = countdownSeconds;
$scope.millis = countdownSeconds * 1000;
calculateTimeUnits();
});
} else {
$scope.millis = 0;
}
calculateTimeUnits();
var tick = function () {
$scope.millis = new Date() - $scope.startTime;
var adjustment = $scope.millis % 1000;
if ($scope.endTimeAttr) {
$scope.millis = $scope.endTime - new Date();
adjustment = $scope.interval - $scope.millis % 1000;
}
if ($scope.countdownattr) {
$scope.millis = $scope.countdown * 1000;
}
if ($scope.millis < 0) {
$scope.stop();
$scope.millis = 0;
calculateTimeUnits();
if($scope.finishCallback) {
$scope.$eval($scope.finishCallback);
}
return;
}
calculateTimeUnits();
//We are not using $timeout for a reason. Please read here - https://github.com/siddii/angular-timer/pull/5
$scope.timeoutId = setTimeout(function () {
tick();
$scope.$digest();
}, $scope.interval - adjustment);
$scope.$emit('timer-tick', {timeoutId: $scope.timeoutId, millis: $scope.millis});
if ($scope.countdown > 0) {
$scope.countdown--;
}
else if ($scope.countdown <= 0) {
$scope.stop();
if($scope.finishCallback) {
$scope.$eval($scope.finishCallback);
}
}
};
if ($scope.autoStart === undefined || $scope.autoStart === true) {
$scope.start();
}
}]
};
}]);
/* commonjs package manager support (eg componentjs) */
if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){
module.exports = timerModule;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="row" ng-app="dashboardApp">
<div class="col-md-12"><div class="row" ng-controller="timingController">
<div class="col-md-12">
<p>
<h3>Timer 1: <timer autostart="false" /></h3>
<h3>Timer 2: <timer autostart="false" interval="2000"/></h3>
<h3>Timer 3: <timer autostart="false">{{minutes}} minutes, {{seconds}} seconds.</timer></h3>
<button type="button" ng-click="startTimer()" ng-show="!timerRunning" ng-disabled="timerRunning" class="btn btn-success btn-lg btn-block" id="start-timer">Start Timer</button>
<button type="button" ng-click="resumeTimer()" ng-show="!timerRunning" ng-disabled="timerRunning" class="btn btn-success btn-lg btn-block" id="resume-timer">Resume Timer</button>
<button type="button" ng-click="stopTimer()" ng-show="timerRunning" ng-disabled="!timerRunning" class="btn btn-danger btn-lg btn-block" id="stop-timer">Stop Timer</button>
<button type="button" class="btn btn-danger btn-lg btn-block" id="reset-timer" style="display:none;">Reset Timer</button>
</p>
</div>
</div>
</div>
</div>

Related

Custom angular directive controller not updating

I created my own angular directive which can simply be used as:
<basket-summary></basket-summary>
This element is used on my master template page (the index.html).
The directive is as follows:
/* Directive */
angular.module('ecommerceDirectives').directive('basketSummary', [function() {
return {
restrict : 'E',
scope: {},
replace: true,
controller : 'BasketController',
controllerAs: 'basketController',
bindToController: {
basketController : '='
},
templateUrl: function(element, attrs) {
if (typeof attrs.templateUrl == 'undefined') {
return 'app/views/basket-summary.html';
} else {
return attrs.templateUrl;
}
},
link: function (scope, element, attrs) {
console.log("test");
}
};
}]);
The templateUrl of this directive is as follows:
<div class="btn-group pull-right">
<a class="btn btn-warning" ng-click="basketController.viewBasket()"><span class="badge">{{basketController.getTotalQuantities()}}</span> <span class="hidden-xs">Shopping</span> Cart</a>
<button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown">
<span class="fa fa-caret-down"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<div class="dropdown-menu">
<div class="col-xs-12 cartItemHeader">
<h4>My Shopping Cart</h4>
</div>
<div class="quickCart" ng-repeat="cartItem in basketController.customerBasket.items">
<div class="col-xs-12 cartItemWrap">
<div class="col-xs-12 desc">{{cartItem.product.title}}</div>
<div class="col-xs-5 col-sm-8 price">{{cartItem.product.rrp_currency}} {{cartItem.product.rrp_amount}}</div>
<div class="col-xs-6 col-sm-3 units">Items: {{cartItem.quantity}}</div>
<div class="col-xs-1 trash"><a ng-click="basketController.deleteCartItem(cartItem.product.id)"><i class="fa fa-trash"></i></a></div>
</div>
</div>
</div>
And the BasketController is as follows:
/* Controller */
angular.module('ecommerceControllers').controller('BasketController', ['$rootScope', '$scope', '$route', '$location', 'CustomerBasketService', 'AppSettingService', 'StorageService', 'DEFAULT_CURRENCY_CODE', 'MERCHANT_ID_KEY', function($rootScope, $scope, $route, $location, CustomerBasketService, AppSettingService, StorageService, DEFAULT_CURRENCY_CODE, MERCHANT_ID_KEY) {
function basketProduct(product) {
this.id = product.id;
this.title = product.title;
this.categories = product.categories;
this.images = product.imaes;
this.created_on = product.created_on;
this.sku_code = product.sku_code;
this.lang = product.lang;
this.short_description = product.short_description;
this.attributes = product.attributes;
this.rrp_currency = product.rrp_currency;
this.rrp_amount = product.rrp_amount;
this.barcode_number = product.barcode_number;
this.last_modified_on = product.last_modified_on;
}
function basketItem(quantity, product) {
this.quantity = quantity;
this.product = new basketProduct(product);
}
function load() {
var basket = StorageService.get("customer_basket");
if (basket) {
for (var i = 0; i < basket.items.length; i++) {
var cartItem = basket.items[i];
cartItem = new basketItem(cartItem.quantity, cartItem.product);
basket.items[i] = cartItem;
}
}
return basket;
}
var basketController = this;
$scope.basketController = basketController;
basketController.customerBasket = load();
if (!basketController.customerBasket) {
basketController.customerBasket = {
shipping : null,
taxRate : null,
tax : null,
items : []
};
}
basketController.addCartItem = function(quantity, product) {
if (product == undefined || product == null) {
throw "No Product was specified.";
}
if (quantity == undefined || quantity == null) {
quantity = null;
}
var found = false;
if (basketController.customerBasket && basketController.customerBasket.items && basketController.customerBasket.items.length > 0) {
for (var i = 0; i < basketController.customerBasket.items.length; i++) {
var cartItem = basketController.customerBasket.items[i];
if (product.id === cartItem.product.id) {
found = true;
cartItem.quantity = cartItem.quantity + quantity;
if (cartItem.quantity < 1) {
basketController.customerBasket.items.splice(i, 1);
} else {
$rootScope.$broadcast('customerBasketItemUpdated', {item: cartItem});
}
}
}
}
if (!found) {
var cartItem = new basketItem(quantity, product);
basketController.customerBasket.items.push(cartItem);
$rootScope.$broadcast('customerBasketItemAdded', {item: cartItem});
}
basketController.saveBasket();
}
basketController.updateBasket = function() {
if (basketController.customerBasket && basketController.customerBasket.items && basketController.customerBasket.items.length > 0) {
for (var i = 0; i < basketController.customerBasket.items.length; i++) {
var cartItem = basketController.customerBasket.items[i];
if (cartItem.quantity < 1) {
basketController.customerBasket.items.splice(i, 1);
}
}
}
basketController.saveBasket();
}
basketController.deleteCartItem = function(productId) {
if (productId == undefined) {
throw "Product ID is required.";
}
if (basketController.customerBasket && basketController.customerBasket.items && basketController.customerBasket.items.length > 0) {
for (var i = 0; i < basketController.customerBasket.items.length; i++) {
var cartItem = basketController.customerBasket.items[i];
if (productId == cartItem.product.id) {
basketController.customerBasket.items.splice(i, 1);
}
}
}
//Save
basketController.saveBasket();
}
basketController.getCurrencyCode = function() {
var code = DEFAULT_CURRENCY_CODE;
if (basketController.customerBasket && basketController.customerBasket.items && basketController.customerBasket.items.length > 0) {
code = basketController.customerBasket.items[0].product.rrp_currency;
}
return code;
};
basketController.getTotalQuantities = function(id) {
var total = 0;
if (basketController.customerBasket && basketController.customerBasket.items && basketController.customerBasket.items.length > 0) {
for (var i = 0; i < basketController.customerBasket.items.length; i++) {
var cartItem = basketController.customerBasket.items[i];
if (id == undefined || id == cartItem.product.id) {
total += cartItem.quantity;
}
}
}
return total;
};
basketController.getTotalAmount = function(cartItem) {
var total = 0;
if (cartItem) {
total = (cartItem.quantity * cartItem.product.rrp_amount);
}
return total.toFixed(2);
};
basketController.getFinalTotalAmount = function() {
var total = 0;
if (basketController.customerBasket && basketController.customerBasket.items && basketController.customerBasket.items.length > 0) {
for (var i = 0; i < basketController.customerBasket.items.length; i++) {
var cartItem = basketController.customerBasket.items[i];
total += (cartItem.quantity * cartItem.product.rrp_amount);
}
}
return total.toFixed(2);
};
basketController.clearBasket = function() {
StorageService.set("customer_basket", null);
basketController.customerBasket = {
shipping : null,
taxRate : null,
tax : null,
items : []
};
$rootScope.$broadcast('customerBasketCleared', {});
}
basketController.saveBasket = function() {
if (basketController.customerBasket) {
StorageService.set("customer_basket", basketController.customerBasket);
$rootScope.$broadcast('customerBasketSaved', {});
}
}
basketController.checkout = function(serviceName, clearCart) {
if (serviceName == undefined || serviceName == null) {
serviceName = "PayPal";
}
switch (serviceName) {
case "PayPal":
basketController.checkoutPayPal(clearCart);
break;
default:
throw "Unknown checkout service '" + serviceName + "'.";
}
};
basketController.checkoutPayPal = function(clearCart) {
if (basketController.customerBasket && basketController.customerBasket.items && basketController.customerBasket.items.length > 0) {
// global data
var data = {
cmd: "_cart",
business: '', //parms.merchantID,
upload: "1",
rm: "2",
charset: "utf-8"
};
AppSettingService.getAppSetting(MERCHANT_ID_KEY).get().$promise
.then(function(result) {
data.business = result.value;
for (var i = 0; i < basketController.customerBasket.items.length; i++) {
var cartItem = basketController.customerBasket.items[i];
var ctr = i + 1;
data["item_number_" + ctr] = cartItem.product.sku_code;
data["item_name_" + ctr] = cartItem.product.title;
data["quantity_" + ctr] = cartItem.quantity;
data["amount_" + ctr] = cartItem.product.rrp_amount.toFixed(2);
}
// build form
var form = $('<form/></form>');
form.attr("action", "https://www.paypal.com/cgi-bin/webscr");
form.attr("method", "POST");
form.attr("style", "display:none;");
addFormFields(form, data);
$("body").append(form);
// submit form
form.submit();
form.remove();
if (clearCart) {
try {
basketController.clearBasket();
} catch (exception) {
}
}
}).catch(function(reason) {
console.log(reason);
});
}
};
basketController.viewBasket = function() {
$location.path("/basket");
$route.reload();
};
function addFormFields(form, data) {
if (data != null) {
$.each(data, function (name, value) {
if (value != null) {
var input = $("<input></input>").attr("type", "hidden").attr("name", name).val(value);
form.append(input);
}
});
}
}
return basketController;
}]);
My dilemma is as follows:
On my product page, I have product.html page (which is an angular view) and the "add to cart" button adds item to the cart but it doesn't update my cart summary button.
How do I make it that when I click the "add to cart" button that it update my cart and the number of items added to the cart?
The example image:
As you can see the orange button at the top right says that I have no items but there is 3 items in my cart already.
I tried various scoping allowed in directives but I seem to be failing to make it work.
PS: I am a newbie in AngularJS so please make your answer as simple to understand. :-)
The view product.html is linked to BasketController and this is the button that add item to cart.
<a class="btn btn-success btn-lg pull-right" role="button" ng-click="basketController.addCartItem(1, productController.selectedProduct)"><i class="fa fa-plus"></i> Add To Cart</a></div>
You have an isolated scope issue. The controller of your directive is not the same as the controller you want to use in your product page. See: scopes
I would suggest you to create a factory, which is always a singleton where you store your basket products and inject them in both, the directive and the products page

Converting CSS Sticky Plugin Into Angular Directive

I am trying to use this Sticky CSS plugin with an Angular Directive. I tried wrapping this code into a Directive but no luck yet getting it to work.
Here is the CodePen of the plugin without Angular - http://codepen.io/chrissp26/pen/gBrdo
and this is what I have so far.
Any help or guidance would be greatly appreciated.
app.directive('sticky', function() {
return function stickyTitles(stickies) {
this.load = function() {
stickies.each(function(){
var thisSticky = jQuery(this).wrap('<div class="followWrap" />');
thisSticky.parent().height(thisSticky.outerHeight());
jQuery.data(thisSticky[0], 'pos', thisSticky.offset().top);
});
}
this.scroll = function() {
stickies.each(function(i){
var thisSticky = jQuery(this),
nextSticky = stickies.eq(i+1),
prevSticky = stickies.eq(i-1),
pos = jQuery.data(thisSticky[0], 'pos');
if (pos <= jQuery(window).scrollTop()) {
thisSticky.addClass("fixed");
if (nextSticky.length > 0 && thisSticky.offset().top >= jQuery.data(nextSticky[0], 'pos') - thisSticky.outerHeight()) {
thisSticky.addClass("absolute").css("top", jQuery.data(nextSticky[0], 'pos') - thisSticky.outerHeight());
}
} else {
thisSticky.removeClass("fixed");
if (prevSticky.length > 0 && jQuery(window).scrollTop() <= jQuery.data(thisSticky[0], 'pos') - prevSticky.outerHeight()) {
prevSticky.removeClass("absolute").removeAttr("style");
}
}
});
}
}
return function(){
var newStickies = new stickyTitles(jQuery(".followMeBar"));
newStickies.load();
jQuery(window).on("scroll", function() {
newStickies.scroll();
});
};
});
try this:
<sticky>
<div class="followMeBar">a</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">b</div>
</sticky>
directive:
app.directive('sticky', function() {
var stickyTitles = function (stickies) {
this.load = function() {
stickies.each(function() {
var thisSticky = jQuery(this).wrap('<div class="followWrap" />');
thisSticky.parent().height(thisSticky.outerHeight());
jQuery.data(thisSticky[0], 'pos', thisSticky.offset().top);
});
}
this.scroll = function() {
stickies.each(function(i) {
var thisSticky = jQuery(this),
nextSticky = stickies.eq(i + 1),
prevSticky = stickies.eq(i - 1),
pos = jQuery.data(thisSticky[0], 'pos');
if (pos <= jQuery(window).scrollTop()) {
thisSticky.addClass("fixed");
if (nextSticky.length > 0 && thisSticky.offset().top >= jQuery.data(nextSticky[0], 'pos') - thisSticky.outerHeight()) {
thisSticky.addClass("absolute").css("top", jQuery.data(nextSticky[0], 'pos') - thisSticky.outerHeight());
}
} else {
thisSticky.removeClass("fixed");
if (prevSticky.length > 0 && jQuery(window).scrollTop() <= jQuery.data(thisSticky[0], 'pos') - prevSticky.outerHeight()) {
prevSticky.removeClass("absolute").removeAttr("style");
}
}
});
}
}
return {
restrict: 'E',
link: function(scope, element, attrs) {
var newStickies = new stickyTitles($(element).find(".followMeBar"));
newStickies.load();
jQuery(window).on("scroll", function() {
newStickies.scroll();
});
}
};
http://plnkr.co/edit/13w5e7n0ReWoaO8513K5?p=preview

{{numPages}} not being calculated by pagination directive

I was under the impression with the pagination directive that the {{numPages}} value would be calculated by the directive. It isn't returning anything for me.
Is there anything I am missing to get this working properly? I don't want to have to calculate it, if the directive is supposed to be doing this for me. Otherwise paging is working great.
<pagination
total-items="totalItems"
ng-model="currentPage"
max-size="maxSize"
items-per-page="itemsPerPage"
class="pagination-sm"
boundary-links="true" rotate="false">
</pagination>
<table class="table table-striped">
<tr>
<td style="width:150px;">GPT ID</td>
<td style="width:250px;">Therapy Area</td>
<td style="width:450px;">GPT Description</td>
<td style="width:150px;">Actions</td>
</tr>
<tr ng-repeat="prGpt in prGpts | orderBy:['therapyArea.therapyArea','gptDesc'] | startFrom:(currentPage -1) * itemsPerPage | limitTo: itemsPerPage">
<td>{{prGpt.id}}</td>
<td>
<span ng-if="!prGpt.editMode">{{prGpt.therapyArea.therapyArea}}</span>
<span ng-if="prGpt.editMode && !createMode">
<select class="form-control" style="width:150px;" ng-model="selectedGpt.therapyArea" ng-options="item as item.therapyArea for item in therapyAreas"/>
</span>
</td>
<td>
<span ng-if="!prGpt.editMode">{{prGpt.gptDesc}}</span>
<span ng-if="prGpt.editMode && !createMode"><input class="form-control" type="text" style="width:400px;" ng-model="selectedGpt.gptDesc" /></span>
</td>
<td>
<span ng-if="!prGpt.editMode" class="glyphicon glyphicon-pencil" ng-click="copySelectedGpt(prGpt);beginEditGpt()"/>
<span ng-if="prGpt.editMode && !createMode" class="glyphicon glyphicon-floppy-disk" ng-click="saveEditGpt()"/>
<span ng-if="prGpt.editMode && !createMode" class="glyphicon glyphicon-thumbs-down" ng-click="cancelEditGpt()"/>
<span ng-if="!prGpt.editMode && !createMode" class="glyphicon glyphicon-remove-circle" ng-click="copySelectedGpt(prGpt);openDeleteDialog()"/>
<span><a ng-href="#!pr/gptProjects/{{prGpt.id}}">Edit Projects</a>
</span>
</tr>
</table>
<br/>
<pre>Page: {{currentPage}} / {{numPages}}</pre>
</div>
controller:
// GPT List Controller
.controller('prGPTCtrl',['$scope', '$modal', '$dialog', 'Restangular', 'prTAService', 'prGPTService', function($scope, $modal, $dialog, Restangular, prTAService, prGPTService) {
// window.alert('prGPTCtrl');
$scope.prGpts = {};
$scope.therapyAreas = {};
$scope.createMode = false;
$scope.selectedGpt = {};
$scope.newGpt = {};
// pagination
$scope.currentPage = 1;
$scope.itemsPerPage = 10;
$scope.maxSize = 20;
$scope.totalItems = $scope.prGpts.length;
Restangular.setBaseUrl('resources/pr');
//call the TA service to get the TA list for the drop down lists
//and then get the gpt list once successful
prTAService.getTAs().then(function(tas) {
$scope.therapyAreas = tas;
prGPTService.getGPTs().then(function(gpts) {
//window.alert('prGPTCtrl:getGPTs');
$scope.prGpts = gpts;
});
});
$scope.$watch('prGpts.length', function(){
$scope.totalItems = $scope.prGpts.length;
});
/*
* Take a copy of the selected GPT to copy in
*/
$scope.copySelectedGpt = function(prGpt) {
$scope.selectedGpt = Restangular.copy(prGpt);
};
$scope.beginEditGpt = function() {
var gpt = {};
var ta = {};
var gpt;
for(var i = 0; i < $scope.prGpts.length;i++) {
gpt = $scope.prGpts[i];
gpt.editMode = false;
}
var index = _.findIndex($scope.prGpts, function(b) {
return b.id === $scope.selectedGpt.id;
});
gpt = $scope.prGpts[index];
gpt.editMode = true;
var taIndex = _.findIndex($scope.therapyAreas, function(b) {
return b.id === $scope.selectedGpt.therapyArea.id;
});
ta = $scope.therapyAreas[taIndex];
$scope.selectedGpt.therapyArea = ta;
$scope.createMode = false;
};
$scope.cancelEditGpt = function() {
var gpt;
for(var i = 0; i < $scope.prGpts.length;i++) {
gpt = $scope.prGpts[i];
gpt.editMode = false;
}
var index = _.findIndex($scope.prGpts, function(b) {
return b.id === $scope.selectedGpt.id;
});
$scope.selectedGpt = null;
$scope.prGpts[index].editMode = false;
};
$scope.saveEditGpt = function() {
$scope.selectedGpt.save().then(function (gpt) {
// find the index in the array which corresponds to the current copy being edited
var index = _.findIndex($scope.prGpts, function(b) {
return b.id === $scope.selectedGpt.id;
});
$scope.prGpts[index] = $scope.selectedGpt;
$scope.prGpts[index].editMode = false;
$scope.selectedGpt = null;
},
function(err) {
window.alert('Error occured: ' + err);
}
);
};
// create a new GPT
$scope.createGpt = function() {
$scope.createMode = true;
var gpt;
for(var i = 0; i < $scope.prGpts.length;i++) {
gpt = $scope.prGpts[i];
gpt.editMode = false;
}
};
$scope.saveNewGpt = function() {
Restangular.all('/gpt/gpts').post($scope.newGpt).then(function(gpt) {
$scope.newGpt = {};
$scope.prGpts.push(gpt);
$scope.createMode = false;
// window.alert('created new GPT ' + gpt.gptDesc + ' with id ' + gpt.id);
});
};
$scope.openDeleteDialog = function() {
var title = "Please confirm deletion of GPT " + $scope.selectedGpt.gptDesc;
var msg = "<b>Delete GPT? Please confirm...</b>";
var btns = [{result:'CANCEL', label: 'Cancel'},
{result:'OK', label: 'OK', cssClass: 'btn-primary'}];
$dialog.messageBox(title, msg, btns, function(result) {
if (result === 'OK') {
$scope.deleteGpt();
}
});
};
$scope.deleteGpt = function() {
$scope.selectedGpt.remove().then(function() {
$scope.prGpts = _.without($scope.prGpts, _.findWhere($scope.prGpts, {id: $scope.selectedGpt.id}));
$scope.selectedGpt = null;
},
function() {
window.alert("There was an issue trying to delete GPT " + $scope.selectedGpt.gptDesc);
}
);
};
}]);
I have a startFrom filter.
.filter('startFrom', function () {
return function (input, start) {
if (input === undefined || input === null || input.length === 0
|| start === undefined || start === null || start.length === 0 || start === NaN) return [];
start = +start; //parse to int
try {
var result = input.slice(start);
return result;
} catch (e) {
// alert(input);
}
};
})
Regards
i
Looks like you're just missing num-pages="numPages" on your <pagination> tag. Essentially you have to provide a variable to pagination in which to return the number of pages. This is done via num-pages
<pagination
num-pages="numPages" <!-- Add this here -->
total-items="totalItems"
ng-model="currentPage"
max-size="maxSize"
items-per-page="itemsPerPage"
class="pagination-sm"
boundary-links="true" rotate="false">
</pagination>

How to update angular progress bar every time I click

Hi I am using angular progress bar and I want to update every time I click a button.
<div ng-controller="ProgressDemoCtrl">
<br/>
<h3>
Dynamic
<button class="btn btn-sm btn-primary" ng-click="random()" type="button">Randomize</button>
</h3>
<small>
<em>No animation</em>
</small>
<progressbar animate="false" type="success" value="dynamic">
<b>{{dynamic}}%</b>
</progressbar>
</div>
ANGULAR
var ProgressDemoCtrl = function ($scope) {
$scope.max = 00;
$scope.random = function() {
var value = Math.floor((Math.random() * 100) + 1);
var type;
if (value < 25) {
type = 'success';
} else if (value < 50) {
type = 'info';
} else if (value < 75) {
type = 'warning';
} else {
type = 'danger';
}
$scope.showWarning = (type === 'danger' || type === 'warning');
$scope.dynamic = value;
$scope.type = type;
};
$scope.random();
$scope.randomStacked = function() {
$scope.stacked = [];
var types = ['success', 'info', 'warning', 'danger'];
for (var i = 0, n = Math.floor((Math.random() * 4) + 1); i < n; i++) {
var index = Math.floor((Math.random() * 4));
$scope.stacked.push({
value: Math.floor((Math.random() * 30) + 1),
type: types[index]
});
}
};
$scope.randomStacked();
};
as you can see in here what it does when i click the button is filling it up randomly.So what i want to do is be able to click a button and update the progress bar.
If you are using angular bootstrap's progressbar this is very easy. I just made a plunkr for it.
Your HTML
<div ng-controller="ProgressDemoCtrl">
<h3>Progress bar value is {{dynamic}}</h3>
<progressbar max="max" value="dynamic">
<span style="color:black; white-space:nowrap;">
{{dynamic}} / {{max}}
</span>
</progressbar>
<input type="button" ng-click="progress()" value="Click Me To Progress" />
</div>
</body>
</html>
and JS
angular.module('plunker', ['ui.bootstrap']);
var ProgressDemoCtrl = function ($scope) {
$scope.dynamic = 10;
$scope.max = 100;
$scope.progress = function(){
$scope.dynamic = $scope.dynamic + 10;
};
};

How to do the Logic behind the next button in angularjs wizard

I have a customers.create.html partial bound to the WizardController.
Then I have 3 customers.create1,2,3.html partial files bound to WizardController1,2,3
Each WizardController1,2 or 3 has an isValid() function. This function determines wether the user can proceed to the next step.
The next button at the bottom of the pasted html should be disabed if ALL ? isValid() functions are false...
Thats my question but the same time that seems not correct to me.
I guess I am not doing the Wizard correctly...
Can someone please guide me how I should proceed with the architecture that the bottom next button is disabled when the current step isValid function returns false, please.
How can I make a connection from the WizardController to any of the WizardController1,2 or 3 ?
Is Firing an event like broadcast a good direction?
<div class="btn-group">
<button class="btn" ng-class="{'btn-primary':isCurrentStep(0)}" ng-click="setCurrentStep(0)">One</button>
<button class="btn" ng-class="{'btn-primary':isCurrentStep(1)}" ng-click="setCurrentStep(1)">Two</button>
<button class="btn" ng-class="{'btn-primary':isCurrentStep(2)}" ng-click="setCurrentStep(2)">Three</button>
</div>
<div ng-switch="getCurrentStep()" ng-animate="'slide'" class="slide-frame">
<div ng-switch-when="one">
<div ng-controller="WizardController1" ng-include src="'../views/customers.create1.html'"></div>
</div>
<div ng-switch-when="two">
<div ng-controller="WizardController2" ng-include src="'../views/customers.create2.html'"></div>
</div>
<div ng-switch-when="three">
<div ng-controller="WizardController3" ng-include src="'../views/customers.create3.html'"></div>
</div>
</div>
<a class="btn" ng-click="handlePrevious()" ng-show="!isFirstStep()">Back</a>
<a class="btn btn-primary" ng-disabled="" ng-click="handleNext(dismiss)">{{getNextLabel()}}</a>
'use strict';
angular.module('myApp').controller('WizardController', function($scope) {
$scope.steps = ['one', 'two', 'three'];
$scope.step = 0;
$scope.wizard = { tacos: 2 };
$scope.isFirstStep = function() {
return $scope.step === 0;
};
$scope.isLastStep = function() {
return $scope.step === ($scope.steps.length - 1);
};
$scope.isCurrentStep = function(step) {
return $scope.step === step;
};
$scope.setCurrentStep = function(step) {
$scope.step = step;
};
$scope.getCurrentStep = function() {
return $scope.steps[$scope.step];
};
$scope.getNextLabel = function() {
return ($scope.isLastStep()) ? 'Submit' : 'Next';
};
$scope.handlePrevious = function() {
$scope.step -= ($scope.isFirstStep()) ? 0 : 1;
};
$scope.handleNext = function(dismiss) {
if($scope.isLastStep()) {
dismiss();
} else {
$scope.step += 1;
}
};
});
durandalJS wizard sample code which could be used to rewrite a wizard for angularJS:
define(['durandal/activator', 'viewmodels/step1', 'viewmodels/step2', 'knockout', 'plugins/dialog', 'durandal/app', 'services/dataservice'],
function (activator, Step1, Step2, ko, dialog, app, service) {
var ctor = function (viewMode, schoolyearId) {
debugger;
if (viewMode === 'edit') {
service.editSchoolyear(schoolyearId);
}
else if (viewMode === 'create') {
service.createSchoolyear();
}
var self = this;
var steps = [new Step1(), new Step2()];
var step = ko.observable(0); // Start with first step
self.activeStep = activator.create();
var stepsLength = steps.length;
this.hasPrevious = ko.computed(function () {
return step() > 0;
});
self.caption = ko.observable();
this.activeStep(steps[step()]);
this.hasNext = ko.computed(function () {
if ((step() === stepsLength - 1) && self.activeStep().isValid()) {
// save
self.caption('save');
return true;
} else if ((step() < stepsLength - 1) && self.activeStep().isValid()) {
self.caption('next');
return true;
}
});
this.isLastStep = function() {
return step() === stepsLength - 1;
}
this.next = function() {
if (this.isLastStep()) {
$.when(service.createTimeTable())
.done(function () {
app.trigger('savedTimeTable', { isSuccess: true });
})
.fail(function () {
app.trigger('savedTimeTable', { isSuccess: false });
});
}
else if (step() < stepsLength) {
step(step() + 1);
self.activeStep(steps[step()]);
}
}
this.previous = function() {
if (step() > 0) {
step(step() - 1);
self.activeStep(steps[step()]);
}
}
}
return ctor;
});

Resources