optimise angular duplicate code - javascript

How can i optimise the duplicate code here
angular.module('myApp')
.controller('LogsController', function ($scope, LogsService) {
$scope.updatingLogs = true;
$scope.loggers = {};
LogsService.findAll().$promise.then(function(data) {
$scope.loggers = data;
$scope.updatingLogs = false;
});
$scope.changeLevel = function (name, level) {
LogsService.changeLevel({name: name, level: level}, function () {
$scope.updatingLogs = true;
LogsService.findAll().$promise.then(function(data) {
$scope.loggers = data;
$scope.updatingLogs = false;
});
});
};
});

Here is a suggestion:
angular.module('myApp')
.controller('LogsController', function ($scope, LogsService) {
$scope.updatingLogs;
$scope.loggers = LogsService.findAll();
$scope.changeLevel = function (name, level) {
$scope.updatingLogs = LogsService.changeLevel({name: name, level: level}, function () {
LogsService.findAll().$promise.then(function(data) {
$scope.loggers = data;
$scope.updatingLogs = null;
});
});
};
});

You could do create $scope.findAll method which will make an ajax of LogsService.findAll() so that you could be utilize this function while doing it multiple times from elsewhere.Optimize version would be.
Code
angular.module('myApp')
.controller('LogsController', function($scope, LogsService) {
$scope.updatingLogs = true;
$scope.loggers = {};
$scope.findAll = function() {
LogsService.findAll().$promise.then(function(data) {
$scope.loggers = data;
$scope.updatingLogs = false;
});
}
$scope.changeLevel = function(name, level) {
LogsService.changeLevel({
name: name,
level: level
}, function() {
$scope.updatingLogs = true;
$scope.findAll();
});
};
$scope.findAll(); //init
});

Depends on what you're reaching for. If you're looking for code clarity, a potential refactor might look something like this.
angular.module('myApp')
.controller('LogsController', function ($scope, LogsService) {
activate();
$scope.changeLevel = function (name, level) {
LogsService.changeLevel({name: name, level: level}, changelevelHandler);
};
function changeLevelHandler() {
$scope.updatingLogs = true;
getLogs();
}
function getLogs() {
LogsService.findAll().$promise.then(function(data) {updateLoggers(data);});
}
function updateLoggers(data) {
$scope.loggers = data;
$scope.updatingLogs = false;
}
function activate() {
$scope.updatingLogs = true;
$scope.loggers = {};
getLogs();
}
});

Related

How do I pre-cache url content in ionic 1/angular 1?

I am pretty new to ionic and working on an app where you load a bunch of categories ,followed by a list of items in the category and when you click on the item in the category a documenturl loads containing the content which is basically an image. Currently, everything loads fine, but I would like to preload the content the moment my category is visible, so even if I go offline I should be able to click on any of the items within the category list and load the respective document. I looked online but I couldn't find anything except localstorage which caches data after you have visited it and not before. Is there a way I can pre-load or pre-cache content ?
Here's my code for controllers:
angular.module('starter.controllers', ["utility.services"])
.directive("bindCompiledHtml", ["$compile", "zoomPerOrientation", function($compile, zoomPerOrientation) {
return {
template: '<div></div>',
scope: {
rawHtml: '=bindCompiledHtml'
},
link: function(scope, elem, attrs) {
scope.$watch('rawHtml', function(value) {
if (!value) return;
var newElem = $compile(value)(scope.$parent);
elem.contents().remove();
zoomPerOrientation.zoomTo('docScroll');
elem.append(newElem);
elem.bind("click", function(e) {
e.stopPropagation();
e.preventDefault();
if (e.target.tagName === 'A') {
window.open(encodeURI(e.target.href), '_system', "presentationstyle=fullscreen,closebuttoncaption=close,location=no,transitionstyle=fliphorizontal");
return false;
} else if (e.target.parentNode.tagName === 'A') {
window.open(encodeURI(e.target.parentNode.href), '_system', "presentationstyle=fullscreen,closebuttoncaption=close,location=no,transitionstyle=fliphorizontal");
return false;
}
});
});
}
};
}])
.directive('setHeight', function($window) {
return {
link: function(scope, element, attrs) {
element.css('height', $window.innerHeight + 30);
}
}
})
.controller("MenuCtrl", ["$scope", "MenuService", "$stateParams", "$state", "ConfigUrls", function($scope, MenuService, $stateParams, $state, ConfigUrls) {
// debugger;
console.log("MenuCtrl");
$scope.menuData = [];
$scope.noMenuDataMsg = "Loading....";
$scope.LoadMenu = function(forceLoad) {
console.log("MenuCtrl - LoadMenu");
// console.log(MenuService.getClinicalAreas(forceLoad));
MenuService.getClinicalAreas(forceLoad).then(function(data) {
$scope.menuData = data;
}, function(err) {
console.log(err);
if (err.error === "timeout") {
$scope.noMenuDataMsg = "Error: Unable to retrieve data due to network error! Please try again when you are in network."
} else {
$scope.noMenuDataMsg = "Error retrieving data! Please contact system administrator."
}
$scope.menuData = [];
}).finally(function() {
$scope.$broadcast('scroll.refreshComplete');
});
}
$scope.deviceModel = window.localStorage.getItem("deviceModel");
// console.log(MenuService);
// console.log($scope.menuData);
$scope.title = $stateParams.topTitle;
var metaTag = $stateParams.metaTag;
//console.log(ConfigUrls[metaTag+"Published"]);
if (metaTag !== "") {
window.localStorage.setItem('publishedUrl', ConfigUrls[metaTag + "Published"]);
window.localStorage.setItem('docUrl', ConfigUrls[metaTag + "DocUrl"]);
window.localStorage.setItem('cacheKeyPrefix', metaTag);
$scope.LoadMenu(false);
} else {
$scope.noMenuDataMsg = "Under Construction!";
}
//console.log("metaTag",metaTag);
//if ($stateParams.topTitle === "Transplant") {
// $scope.LoadMenu(false);
//}
//else {
// $scope.noMenuDataMsg = "Under Construction!";
//}
$scope.showHomeItem = function(clinicalArea) {
console.log("MenuCtrl - showHomeItem");
$state.go('contr.home', {
cA: clinicalArea
});
}
$scope.goHome = function() {
console.log("MenuCtrl - goHome");
$state.go('contr.topmenu');
}
}])
.controller("HomeCtrl", ["$scope", "HomeService", "$stateParams", "$state", function($scope, HomeService, $stateParams, $state) {
console.log("HomeCtrl");
$scope.organs = [];
$scope.title = $stateParams.cA;
$scope.LoadHome = function(forceLoad) {
console.log("HomeCtrl - LoadHome");
HomeService.getOrgans($stateParams.cA, forceLoad).then(function(data) {
$scope.organs = data;
}, function(err) {
$scope.organs = [];
}).finally(function() {
$scope.$broadcast('scroll.refreshComplete');
});
}
$scope.showLevel2Item = function(title, clinicalArea) {
console.log("HomeCtrl - showLevel2Item");
$state.go('contr.level2', {
title: title,
cA: clinicalArea
});
//:title/:cA
}
$scope.goHome = function() {
console.log("HomeCtrl - goHome");
$state.go('contr.topmenu');
}
$scope.LoadHome(false);
}])
.controller('Level2Ctrl', ["$scope", "OrganService", "$stateParams", "$state", function($scope, OrganService, $stateParams, $state) {
$scope.title = "Level2 ";
console.log("Level2Ctrl");
$scope.parentOrgan = {};
$scope.viewTitle = $stateParams.title;
OrganService.getSingleOrganDetail($stateParams.cA, $stateParams.title).then(function(data) {
$scope.parentOrgan = data[0];
$scope.parentOrgan.clinicalAreaDisp = "Transplant";
}, function(err) {
$scope.parentOrgan = {};
});
console.log($scope.parentOrgan);
$scope.subGroup = [];
$scope.LoadSubGroups = function(forceLoad) {
console.log("Level2Ctrl - LoadSubGroups");
OrganService.getSubGroups($stateParams.title, $stateParams.cA, forceLoad).then(function(data) {
$scope.subGroup = data;
console.log("$scope.subGroup", $scope.subGroup);
}, function(err) {
$scope.subGroup = [];
}).finally(function() {
$scope.$broadcast('scroll.refreshComplete');
});
}
//$scope.deviceModel = window.localStorage.getItem("deviceModel");
//$scope.devicePlatform = window.localStorage.getItem("devicePlatform");
$scope.toggleGroup = function(group) {
group.show = !group.show;
};
$scope.isGroupShown = function(group) {
return group.show;
};
$scope.showDocumentDtl = function(id, docTitle, sgName, mnGroup, area) {
console.log("Level2Ctrl - showDocumentDtl");
$state.go('contr.doc-dtl', {
id: id,
docTitle: docTitle,
sgName: sgName,
mnGroup: mnGroup,
area: area
});
//:title/:cA
}
$scope.goHome = function() {
console.log("Level2Ctrl - goHome");
$state.go('contr.topmenu');
}
$scope.LoadSubGroups();
}])
.controller('DocumentCtrl', ["$scope", "DocmentService", "zoomPerOrientation", "$stateParams", "$ionicScrollDelegate", "$state", function($scope, DocmentService, zoomPerOrientation, $stateParams, $ionicScrollDelegate, $state) {
$scope.viewData = {};
$scope.snippet = "<p style='margin-top:40%;margin-left:40%;font-weight:bold;font-size:1.6em;' class='item item-stable'>Loading...</p>";
$scope.statusMessage = "";
$scope.title = $stateParams.mnGroup;
console.log("DocumentCtrl");
console.log("$stateParams", $stateParams);
//, $stateParams.docTitle, $stateParams.sgName, $stateParams.mnGroup, $stateParams.area
// console.log("Inside docuemtn controller");
$scope.LoadDocument = function(forceLoad) {
console.log("DocumentCtrl - LoadDocument");
DocmentService.getRowDocument($stateParams.id, $stateParams.docTitle, $stateParams.sgName, $stateParams.mnGroup, $stateParams.area, forceLoad).then(
function(data) {
// console.log("successfull", data);
$scope.viewData = data;
$scope.snippet = $scope.viewData.document;
},
function(reason) {
// console.log("Error Occured", reason);
$scope.viewData = {
"docTitle": "Error Occured!"
};
if (reason.error === "timeout") {
$scope.snippet = "<div style='margin-top:40%;margin-left:15%;font-weight:bold;font-size:1.6em;width:600px !important;padding:16px !important;line-height:120%;' class='item item-stable item-text-wrap item-complex'>Error: Unable to the load the document at this time. Please make sure you are in the network or you have already fetched the document while you were in the network!</div>";
}
// $scope.statusMessage = err;
}).finally(function() {
console.log("finally", data);
$scope.$broadcast('scroll.refreshComplete');
});
}
//below code would be refactored in near future.
//It is not a good practice adding window event listener in the controller
window.addEventListener('orientationchange', function() {
try {
if ($ionicScrollDelegate.$getByHandle('docScroll')._instances.length > 2) {
zoomPerOrientation.zoomTo('docScroll');
}
} catch (exception) {
console.log(exception);
}
});
$scope.goHome = function() {
console.log("DocumentCtrl - goHome");
$state.go('contr.topmenu');
}
$scope.LoadDocument(true);
}])
.controller('TopMenuCtrl', ["$scope", "TopMenuService", "$state", "$ionicHistory",
function($scope, TopMenuService, $state, $ionicHistory) {
$ionicHistory.clearHistory();
$scope.title = "Rules";
$scope.menuItems = [];
$scope.menuItemsLandscape = [];
$scope.flatMenuItems = [];
$scope.tileView = true;
$scope.listView = false;
$scope.portraitMode = true;
console.log("TopMenuCtrl");
TopMenuService.getMenuItems().then(function(data) {
$scope.menuItems = data.colData;
$scope.flatMenuItems = data.flatData;
$scope.menuItemsLandscape = data.threeColData;
console.log($scope.menuItems);
},
function() {
$scope.menuItems = [];
});
$scope.showMenuItem = function(title, metaTag) {
console.log("TopMenuCtrl - showMenuItem");
//$state.go('tab.menu', { topTitle: title });
$state.go('contr.menu', {
topTitle: title,
metaTag: metaTag
});
}
$scope.itemChanged = function() {
console.log("TopMenuCtrl - itemChanged");
console.log($scope.tileView);
if ($scope.tileView) {
$scope.listView = true;
$scope.tileView = false;
} else {
$scope.listView = false;
$scope.tileView = true;
}
}
// console.log(window.orientation);
function onChangeOrientation() {
console.log("TopMenuCtrl - onChangeOrientation");
try {
//landscape mode
// console.log("Orientation Changed");
if (window.orientation === 90 || window.orientation == -90) {
$scope.portraitMode = false;
}
//portrait
else {
$scope.portraitMode = true;
}
} catch (exception) {
console.log(exception);
}
}
onChangeOrientation();
window.addEventListener('orientationchange', function() {
try {
//landscape mode
// console.log("Orientation Changed");
if (window.orientation === 90 || window.orientation == -90) {
$scope.$apply(function() {
$scope.portraitMode = false;
});
}
//portrait
else {
$scope.$apply(function() {
$scope.portraitMode = true;
});
}
} catch (exception) {
console.log(exception);
}
});
}
])
.controller('LoginController', ["$scope", "$location", "$ionicHistory", '$timeout', '$ionicLoading', '$state',
function($scope, $location, $ionicHistory, $timeout, $ionicLoading, $state) {
$scope.username = "Guest";
$scope.password = "Abcd123";
// $ionicNavBarDelegate.showBar(false);
$scope.login = function(password) {
console.log("LoginController - login");
if (password) {
$ionicLoading.show({
content: 'Loading',
animation: 'fade-in',
showBackdrop: true,
template: '<p class="item-icon-left bar-header"><ion-spinner icon="lines"/></p>',
maxWidth: 200,
showDelay: 0
});
window.localStorage.setItem("Pswd", password);
$ionicHistory.nextViewOptions({
disableAnimate: true,
disableBack: true
});
$timeout(function() {
$ionicLoading.hide();
//$location.path("/tab/topmenu");
$state.go('contr.topmenu');
}, 1000);
}
}
}
])
.controller('AccountCtrl', function($scope) {
$scope.settings = {
enableFriends: true
};
});
Please let me know if you need any other info.Also, currently I do support local cache to cache categories locally, but not pre-cached. Is there a way to retrieve these documents beforehand? Please check my loaddocuments section which deals with loading document url's once you click on the specific item.
Please refer this I've already explained everything with programming approach.
StackOverflow Solution Link
You can use this explained approach, and adding for others who are looking for answer to this question.

Angular JS factory function

I want the use set method of factory but both of return default how can I fix that problem?
app.factory("DualListShareFactory", function(){
var selectedArray=[];
return{
getSelectedArray: function () {
return selectedArray;
},
setSelectedArray: function (array){
selectedArray=array;
}
}
});
Using ng-dual List from https://github.com/tushariscoolster/ng-duallist
I'm tkining it not working: DualListShareFactory.setSelectedArray(vm.rightValue);
I use other method for and push but I am received same error .
app.controller("duallist2", function($scope,DualListShareFactory){
var vm=this;
vm.property='duallist2';
activate();
function activate() {
vm.leftValue = [];
vm.rightValue = [];
vm.addValue = [];
vm.removeValue = [];
function loadMoreLeft() {
for (var i = 0; i < $scope.incomingItem.length; i++) {
vm.leftValue.push({
'name': $scope.incomingItem[i]
});
}
};
function loadMoreRight() {
}
vm.options = {
leftContainerScrollEnd: function () {
},
rightContainerScrollEnd: function () {
},
leftContainerSearch: function (text) {
console.log(text)
vm.leftValue = $filter('filter')(leftValue, {
'name': text
})
},
rightContainerSearch: function (text) {
vm.rightValue = $filter('filter')(rightValue, {
'name': text
})
},
leftContainerLabel: 'Gelen Parçalar',
rightContainerLabel: 'Seçilen Parçalar',
onMoveRight: function () {
console.log('right');
console.log(vm.addValue);
},
onMoveLeft: function () {
console.log('left');
console.log(vm.removeValue);
}
};
loadMoreLeft();
var leftValue = angular.copy(vm.leftValue);
var rightValue = angular.copy(vm.rightValue);
} console.log(vm.rightValue);
DualListShareFactory.setSelectedArray(vm.rightValue);
});
I am not this will work but try "this",
app.factory("DualListShareFactory", function(){
this.selectedArray=[];
return{
getSelectedArray: function () {
return this.selectedArray;
},
setSelectedArray: function (array){
this.selectedArray = array;
}
}
});
var app = angular.module("testapp", ["ng-duallist"]);
app.factory("DualListShareFactory", function(){
var selectedArray = [];
return{
getSelectedArray: function () {
return selectedArray
},
setSelectedArray: function (array){
angular.copy(array, selectedArray);
}
}
});
using for this add the other code block before ending function.
onMoveRight: function () {
DualListShareFactory.setSelectedArray(vm.rightValue);
},
onMoveLeft: function () {
DualListShareFactory.setSelectedArray(vm.rightValue);
}
};
loadMoreLeft();
var leftValue = angular.copy(vm.leftValue);
var rightValue = angular.copy(vm.rightValue);

Angular/Jasmin : can't get values passed while testing

I wrote a page that allows me to change my password. The code works and it does everything I want it to do, so I started writing tests. Since I'm not as experienced in Angular testing this had proven to be quite difficult and I can't get passed this error:
TypeError: 'undefined' is not an object (evaluating 'plan.apply')
at /Users/denniegrondelaers/asadventure/myproject-web/src/users/controllers/userPasswordController.js:9
at /Users/denniegrondelaers/asadventure/myproject-web/test/unitTests/specs/users/controllers/userPasswordControllerSpec.js:98
The controller:
userPasswordController.js
users.controllers.controller('userPasswordController',
['$scope', 'Session', '$state', 'UserService', 'languages',
function ($scope, Session, $state, UserService, languages) {
$scope.languages = languages;
$scope.password = "";
$scope.notEqual = false;
$scope.isSuccessful = false;
$scope.changePassword = function() {
var pw = {
userId: Session.getCurrentSession().userId,
oldPassword: encrypt($scope.password.oldPassword),
newPassword: encrypt($scope.password.newPassword),
newPasswordRepeat: encrypt($scope.password.newPasswordRepeat)
};
if (pw.newPassword === pw.newPasswordRepeat) {
$scope.notEqual = false;
UserService.setNewPassword(pw).then(function(res) {
$scope.formErrors = undefined;
$scope.isSuccessful = true;
}, function (error) {
$scope.formErrors = error.data;
}
);
} else {
$scope.notEqual = true;
}
};
var encrypt = function (password) {
var encrypted = CryptoJS.md5(password);
return encrypted.toString(CryptoJS.enc.Hex);
};
}
]
);
The service:
userService.js
userService.setNewPassword = function (password) {
return $http
.put(EnvironmentConfig.endpointUrl +
"/password/change", password)
};
The test:
userPasswordControllerSpec.js
describe('Users', function () {
describe('Controllers', function () {
fdescribe('userPasswordController', function () {
var $scope,
controller,
$q,
willResolve,
mockSession,
mockState,
mockUserService,
mockLanguages;
beforeEach(function () {
module('mysite.users.controllers');
module(function ($provide) {
$provide.value('translateFilter', function (a) {
return a;
});
$provide.value('$state', function (a) {
return a;
});
});
mockSession = {
getCurrentSession: function () {
return {userId: 4};
}
};
mockState = {
params: {
id: 1
},
go: function () {
}
};
mockLanguages = {
getLanguages : function () {
var deferred = $q.defer();
deferred.resolve({
data: [{}]
});
return deferred.promise;
}
};
mockUserService = {
setNewPassword : function () {
var deferred = $q.defer();
if (willResolve) {
deferred.resolve({
data: [{}]
});
}
return deferred.promise;
}
};
inject(function (_$q_, $controller, $rootScope) {
controller = $controller;
$q = _$q_;
$scope = $rootScope.$new();
});
controller('userPasswordController', {$scope: $scope, Session: mockSession, $state: mockState,
UserService: mockUserService, languages: mockLanguages
});
willResolve = true;
});
it('should change password', function () {
spyOn(mockUserService, 'setNewPassword').and.callThrough();
spyOn(mockState, 'go').and.callThrough();
spyOn(mockSession, 'getCurrentSession').and.callFake();
expect(mockUserService.setNewPassword).not.toHaveBeenCalled();
expect($scope.isSubmitable()).not.toBeTruthy();
$scope.compareStoreSelection = function () {
return true;
};
$scope.password = {
oldPassword: "123456",
newPassword: "password",
newPasswordRepeat: "password"
};
expect($scope.isSubmitable()).toBeTruthy();
>>> $scope.changePassword(); <<< LOCATION OF ERROR, line 98
expect(mockUserService.setNewPassword).toHaveBeenCalled();
$scope.$apply();
});
});
});
});
I've marked the line that gives the code in the test.
Anybody any idea how to fix this? A colleague suggested altering my controller code, but I'd like to keep it as it is, since it seems logical that this code shouldn't be altered for testing to work, right?
Solution
Yarons' suggestion to change the mockSession.getCurrentSession.callFake to mockSession.getCurrentSession.callThrough fixed it!

How To Run Controller Functionality Again Using Different Parameters From View ng-model

I have a controller that works fine on initial load. It calls user [0] data and everything processes fine. When I change dropdown, I want to call the same function, but I cannot get the entire controller to reload. It starts from the function call and leaves undefined in places where it pulls correct information (linkToken, etc) on initial load. Is there a way I can get it to reload all data from the controller instead of just from the function?
After calling the testchange() from the view to pass in the new data, I get :
TypeError: Cannot read property 'locations' of undefined
at h.$scope.updateLocations (refillController.js:261)
at refillController.js:73
But, when I call the original getRefills() that is ran on the initial page load I get the same error. How can I define these so the load after the onchange(0)?
angular.module('FinalApp.Controllers').controller('refillController', function ($rootScope, $scope, $location, $modal, userService, dependentsService, accountService, sharedCollections, configurationService, refillsService) {
$scope.user = userService.GetUserInformation();
$scope.userInfoArr = [];
//$scope.tests.push({'Name':$scope.user.FirstName, 'LinkToken':$scope.user.LinkToken});
$scope.userInfoArr = $scope.user.Dependants.map(function(item){return {'Name':item.FirstName, 'LinkToken':item.LinkToken}});
$scope.userInfoArr.splice(0, 0, {'Name': $scope.user.FirstName, 'LinkToken': $scope.user.LinkToken});
console.log($scope.userInfoArr);
$scope.finUserInfoArr = $scope.userInfoArr[0].LinkToken;
$scope.billingInfo = null;
$rootScope.showNavbar = true;
$scope.selectedMethod = null;
$scope.location = null;
$scope.payment = null;
$scope.refills = [];
$scope.deliverTypes = [];
$scope.locations = [];
$scope.payments = [];
$scope.allSelected = false;
$scope.loadingBillingInfo = false;
$scope.isMailOrder = false;
//Detect Mobile Switch Refill List To Grid
if(window.innerWidth <= 800) {
$scope.view = "Grid";
} else {
$scope.view = "List";
}
$scope.changeViewToList = function () {
$scope.view = "List";
};
$scope.changeViewToGrid = function () {
$scope.view = "Grid";
};
$scope.testchange = function(selectedTest) {
$scope.getRefills(selectedTest);
console.log(selectedTest);
};
$scope.getRefills = function (linkToken) {
$scope.allSelected = false;
$scope.loading = true;
refillsService.GetRefills(
linkToken,
$scope.selectedMethod,
$scope.location,
$scope.payment
).then(function (data) {
$scope.refills = [];
_.each(data.Prescriptions, function (item) {
fillRefills(item);
});
fillDeliverTypes(data.DeliveryTypes);
if (!$scope.selectedMethod)
$scope.selectedMethod = data.DeliveryTypeId;
if (!$scope.location)
$scope.location = data.PickupLocationId;
if (!$scope.payment)
$scope.payment = data.PaymentTypeId;
$scope.loading = false;
$scope.updateLocations();
})["catch"](function (error) {
console.log(error);
$scope.loading = false;
alertify.alert(configurationService.ErrorMessage("getting your refills", error.Message));
});
};
var fillRefills = function (item) {
//TODO-CallDoc temp fix
if (item.RefillClass == "CALL_DOCTOR") {
item.NextRefillDate = '1900-01-01T00:00:00'
}
var parsedDate = checkDate(moment(item.NextRefillDate).format('L'));
var lastrefill = checkDate(moment(item.LastDispenseDate).format('L'));
var expireDate = checkDate(moment(item.ExpirationDate).format('L'));
var status = (item.RefillStatus.indexOf("After") == -1) ? item.RefillStatus : "Refill " + item.RefillStatus;
$scope.refills.push({
selected: false,
rx: item.ScriptNo,
name: item.DrugName,
dose: item.UnitsPerDose,
dir: item.Instructions,
nextfill: parsedDate,
lastfill: lastrefill,
refillsLeft: item.NumRefillsLeft,
status: status,
msg: item.RefillMessage,
canSelect: item.IsRefillable,
refillClass: item.RefillClass,
lastDispenseQty: item.LastDispenseQty,
DaysSupply: item.DaysSupply,
expireDate: expireDate,
copayAmt: item.CopayAmt,
drFirstName: item.DoctorFirstName,
drLastName: item.DoctorLastName,
writtenQty: item.WrittenQty
});
};
var checkDate = function (date) {
if (date == "01/01/1900") return "N/A";
if (date == "Invalid Date") return "";
return date;
};
var fillDeliverTypes = function (deliverTypes) {
$scope.deliverTypes = [];
_.each(deliverTypes, function (item) {
$scope.deliverTypes.push({
id: item.DeliveryTypeId,
name: item.DeliveryTypeName,
locations: item.PickupLocations,
payments: item.PaymentTypes
});
});
};
var getBillingInfo = function () {
$scope.loadingBillingInfo = true;
accountService.GetCreditCardInfo().then(function (data) {
$scope.billingInfo = data;
$scope.loadingBillingInfo = false;
})["catch"](function (error) {
$scope.loadingBillingInfo = false;
alertify.alert(configurationService.ErrorMessage("getting account information", error.Message));
});
};
var getAccountInfo = function () {
accountService.GetAccountInfo().then(function (data) {
if (data.StatusCode == "SUCCESS") {
$scope.user = data;
userService.SaveUserInformation(data);
if ($scope.user.IsLinked) {
$rootScope.enableMyRefills = true;
$rootScope.enableMyReports = true;
window.location.hash = "#/refills";
} else {
$rootScope.enableMyRefills = false;
$rootScope.enableMyReports = true;
}
} else {
alertify.alert(configurationService.ErrorMessage("getting account information", data.StatusMessage));
}
})["catch"](function (error) {
alertify.alert(configurationService.ErrorMessage("getting account information", error.Message));
});
};
var openModal = function (viewUrl, controllerUrl, size, payload) {
var modalInstance = $modal.open({
templateUrl: viewUrl,
controller: controllerUrl,
size: size,
resolve: {
data: function () {
return payload;
}
}
});
return modalInstance;
};
$scope.toggleRxSelection = function(rx) {
if (rx.canSelect) {
rx.selected = !rx.selected;
$scope.evaluateAllSelected();
}
};
$scope.selectAll = function (data) {
// $scope.allSelected = allSelected;
_.each($scope.refills, function (x) {
if (x.canSelect) x.selected = data;
});
};
$scope.evaluateAllSelected = function () {
var count = _.countBy(_.where($scope.refills, {canSelect:true}), function(refill) {
return refill.selected ? 'selected' : 'not';
});
$scope.allSelected = (count.not === undefined);
};
$scope.openEditCreditCardInfo = function () {
var payload = ($scope.billingInfo != null && $scope.billingInfo != undefined)
&& $scope.billingInfo.CardNumber != "" ? $scope.billingInfo : {};
if (payload != {}) {
payload.ExpMonth = {id: parseInt(payload.ExpMonth)};
payload.ExpYear = {id: parseInt(payload.ExpYear)};
}
openModal('app/views/editAccount/billingInformation.html', "billingInformationController", "xlg", payload).result.then(function () {
getAccountInfo();
getBillingInfo();
}, function () {
getBillingInfo();
});
};
$scope.openConfirmOrder = function () {
var refillsSelected = _.where($scope.refills, {selected: true});
var location = _.findWhere($scope.locations, {PickupLocationId: $scope.location});
var payment = _.findWhere($scope.payments, {PaymentTypeId: $scope.payment});
var deliver = _.findWhere($scope.deliverTypes, {id: $scope.selectedMethod});
if (refillsSelected.length == 0) {
alertify.error("You need to select at least one refill");
return;
}
if (deliver.id == 10001 && !$scope.user.IsCreditCardOnFile) {
alertify.error("Need credit card on file for mail order");
return;
}
sharedCollections.setRefills(refillsSelected);
sharedCollections.setLocation(location);
sharedCollections.setPayment(payment);
sharedCollections.setDeliver(deliver);
openModal('app/views/refills/confirmOrder.html', "confirmOrderController", "xlg").result.then(function () {
$scope.billingInfo = accountService.GetCreditCardInfo();
$scope.getRefills();
}, function () {
//$scope.billingInfo = accountService.GetCreditCardInfo();
//getRefills();
});
};
$scope.showRefill = function (rx) {
var data = {rx: rx, refills: $scope.refills};
openModal('app/views/refills/showRefills.html', "refillsCarrousel", "xlg", data).result.then(function () {
$scope.evaluateAllSelected();
}, function () {
$scope.evaluateAllSelected();
});
};
$scope.updateLocations = function () {
$scope.locations = _.findWhere($scope.deliverTypes, {id: $scope.selectedMethod}).locations;
$scope.payments = _.findWhere($scope.deliverTypes, {id: $scope.selectedMethod}).payments;
setLocationAndPayment();
};
var setLocationAndPayment = function () {
if ($scope.locations.length == 1) {
$scope.location = $scope.locations[0].PickupLocationId;
}
if ($scope.payments.length == 1) {
$scope.payment = $scope.payments[0].PaymentTypeId;
}
//check for mail order
($scope.selectedMethod == 10001 && !$scope.payment) ? $scope.isMailOrder = true : $scope.isMailOrder = false;
};
$scope.getRefills($scope.finUserInfoArr);
getBillingInfo();
});
Check if your refillsService returns correct data, it could be that $scope.refills remains empty array.

AngularJS - ng-bind not updating

I have a controller which has a function to get some alerts from an API and update a count on the front-end of my site which is bound to the alert.
Unfortunately the ng-bind attribute I'm using doesn't seem to be updating the count live, even though a simple console.log() is telling me that the actual alert count is being updated in the controller.
Front-end
<div class="modeSelector modeSelector_oneUp" data-ng-controller="MyLivestockController as vm">
<a class="modeSelector-mode" data-ui-sref="my-livestock">
<div class="modeSelector-type">Alerts</div>
<img class="modeSelector-icon" src="/inc/img/_icons/envelope-black.svg" onerror="this.src=envelope-black.png" />
<span data-ng-bind="vm.alertCount"></span>
</a>
</div>
Controller
(function() {
'use strict';
function MyLivestockController(userService) {
var vm = this;
vm.myLivestockNotification = {
isLoading: true,
hasError: false
};
vm.alertsNotification = {
isLoading: true,
hasError: false,
hasData: false
};
vm.deleteAlert = function(id) {
vm.currentAlert = void 0;
vm.alertsNotification.isLoading = true;
userService.deleteAlert(vm.user.id, id).then(function() {
// Remove the alert from our Array
vm.alerts = vm.alerts.filter(function(alert) {
return alert.id !== id;
});
// Refresh the alert count for the user
vm.getAlerts(vm.user.id);
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
}, function() {
vm.alertsNotification.hasError = true;
});
};
vm.getAlerts = function(id) {
userService.getAlerts(id).then(function(alertData) {
vm.alertCount = alertData.length;
if (vm.alertCount > 0) {
vm.alertsNotification.hasData = true;
} else {
vm.alertsNotification.hasData = false;
}
vm.alerts = alertData;
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
}, function() {
vm.alertsNotification.hasError = true;
});
};
// Init
(function() {
userService.getCurrentUser().then(function(data) {
vm.myLivestockNotification.hasError = false;
vm.myLivestockNotification.isLoading = false;
vm.user = data;
// Get alert count for the user
vm.getAlerts(vm.user.id);
}, function() {
vm.myLivestockNotification.hasError = true;
});
})();
}
angular
.module('abp')
.controller('MyLivestockController', MyLivestockController);
})();
Service
(function() {
'use strict';
function userService($q, $sessionStorage, $localStorage, $filter, user) {
var service = this;
service.getAlerts = function(id) {
var deferred = $q.defer();
user.alerts({ userID: id }, function(response) {
if (response.hasOwnProperty('data')) {
// Convert dates to valid Date
angular.forEach(response.data, function(alert) {
/* jshint camelcase: false */
if (alert.created_at) {
alert.created_at = $filter('abpDate')(alert.created_at);
/* jshint camelcase: true */
}
});
deferred.resolve(response.data);
}
else {
deferred.reject('DATA ERROR');
}
}, function(e) {
deferred.reject(e);
});
return deferred.promise;
};
angular
.module('abp')
.service('userService', userService);
})();
As you can see, I've got my getAlerts() function being called every time an alert is deleted, using the deleteAlert() function, but the <span data-ng-bind="vm.alertCount"></span> on the front-end only updates after refreshing the page, where I'd like it to update live.
Your bind is not updating because you change the value of alertCount outside of digest cycle of your angular app. When you refresh your app, the digest runs and thus your value gets updated. Wrap the update of the variable in $scope.apply() like so:
$scope.$apply(function(){
vm.alertCount = alertData.length;
});
This will force digest and update the value live.
If you have more values that are updated outside of digest (any callback, promise etc) you can force digest cycle by calling:
$scope.$apply();
Hope it helps.
EDIT -----
Given your update with full code, I see that you are not injecting scope anywhere in your controller, the controllers I write usually start like that:
(function () {
var app = angular.module('mainModule');
app.controller('myController', ['$scope', '$myService', function ($scope, $myService) {
//logic
}]);
}());
EDIT -----
Here is a quick go I had on your code:
(function() {
'use strict';
var app = angular.module('abp');
app.controller('MyLivestockController', ['$scope', 'userService', function($scope, userService) {
var vm = {};
$scope.vm = vm;
vm.myLivestockNotification = {
isLoading: true,
hasError: false
};
vm.alertsNotification = {
isLoading: true,
hasError: false,
hasData: false
};
vm.deleteAlert = function(id) {
vm.currentAlert = void 0;
vm.alertsNotification.isLoading = true;
userService.deleteAlert(vm.user.id, id).then(function() {
// Remove the alert from our Array
vm.alerts = vm.alerts.filter(function(alert) {
return alert.id !== id;
});
// Refresh the alert count for the user
vm.getAlerts(vm.user.id);
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
}, function() {
vm.alertsNotification.hasError = true;
});
};
vm.getAlerts = function(id) {
userService.getAlerts(id).then(function(alertData) {
vm.alertCount = alertData.length;
if (vm.alertCount > 0) {
vm.alertsNotification.hasData = true;
} else {
vm.alertsNotification.hasData = false;
}
vm.alerts = alertData;
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
//important, this is promise so we have to apply the scope to update view
$scope.$apply();
}, function() {
vm.alertsNotification.hasError = true;
});
};
// Init
(function() {
userService.getCurrentUser().then(function(data) {
vm.myLivestockNotification.hasError = false;
vm.myLivestockNotification.isLoading = false;
vm.user = data;
// Get alert count for the user
vm.getAlerts(vm.user.id);
}, function() {
vm.myLivestockNotification.hasError = true;
});
})();
}]);
})();
The general idea is:
you create an app (angular.module)
you create a controller in this app, with $scope injected
any values you want to be updated on your view, you add to $scope
if you have any $scope updates in a callback, event or promise, you wrap them in (or follow with) $scope.$apply call
I think this should work for you :)
I have attempted to reproduce your code below with a mock userService, and some slight modifications to the html view so we can more clearly see the alerts and delete them. I have not modified your Controller.
This appears to work, yes?
Which leads me to believe there may be some issue with the implementation of your userService. If you are able to post the relevant code, I can update this answer with a clarified solution.
UPDATE: As you've updated your question with the userService code, I've updated the below to more closely match. I still have a mock service standing in place of the user dependency of the userService. Additionally I made a couple of small edits to the Controller class so that while promises are still resolving we can see 'Updating...' in place of the alerts count.
This all still appears to work, unless I'm misunderstanding - will think on it more and update this 'answer' when I can think of where else to investigate for the source of the issue, see if we can at least reproduce it!
(function() {
'use strict';
function MyLivestockController(userService) {
var vm = this;
vm.myLivestockNotification = {
isLoading: true,
hasError: false
};
vm.alertsNotification = {
isLoading: true,
hasError: false,
hasData: false
};
vm.deleteAlert = function(id) {
vm.currentAlert = void 0;
vm.alertsNotification.isLoading = true;
return userService.deleteAlert(vm.user.id, id).then(function() {
// Remove the alert from our Array
vm.alerts = vm.alerts.filter(function(alert) {
return alert.id !== id;
});
// Refresh the alert count for the user
vm.getAlerts(vm.user.id).then(function() {
vm.alertsNotification.isLoading = false; //put here, loading isn't really finished until after .getAlerts() is done
vm.alertsNotification.hasError = false;
});
}, function() {
vm.alertsNotification.hasError = true;
});
};
vm.getAlerts = function(id) {
vm.alertsNotification.isLoading = true;
return userService.getAlerts(id).then(function(alertData) { //return the promise so we can chain .then in .deleteAlert()
vm.alertCount = alertData.length;
if (vm.alertCount > 0) {
vm.alertsNotification.hasData = true;
} else {
vm.alertsNotification.hasData = false;
}
vm.alerts = alertData;
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
}, function() {
vm.alertsNotification.hasError = true;
});
};
// Init
(function() {
userService.getCurrentUser().then(function(data) {
vm.myLivestockNotification.hasError = false;
vm.myLivestockNotification.isLoading = false;
vm.user = data;
// Get alert count for the user
vm.getAlerts(vm.user.id);
}, function() {
vm.myLivestockNotification.hasError = true;
});
})();
}
function userMock($q, $timeout, $log) {
var _alerts = {
data: [{
id: 1,
message: "He doesn't sleep, he waits..."
}, {
id: 2,
message: "He doesn't mow his lawn, he stands outside and dares it to grow."
}, {
id: 3,
message: "Some magicians can walk on water. He can swim through land."
}]
},
_currentUser = {
id: 'Q2h1Y2sgTm9ycmlz'
};
return {
getCurrentUser: function getCurrentUser() {
$log.log("getCurrentUser");
//return $q.when(_currentUser);
return $timeout(function() { //use $timeout to simulate some REST API latency...
return _currentUser;
}, 500);
},
getAlerts: function getAlerts(id) {
$log.log("getAlerts: " + id); //not doing anything with the id in this mock...
$log.log(_alerts.data);
//return $q.when(_alerts);
return $timeout(function() {
return _alerts;
}, 500);
},
deleteAlert: function deleteAlert(userId, id) {
$log.log("deleteAlert: " + userId + " :: " + id);
//return $q.when(_alerts);
return $timeout(function() {
for (var i = 0; i < _alerts.data.length; i++) {
if (_alerts.data[i].id === id) {
_alerts.data.splice(i, 1);
$log.log("alert found and deleted");
break;
}
}
$log.log(_alerts.data);
return _alerts;
}, 500);
}
};
}
function userService($q, $timeout, $log, userMock) {
var service = this;
service.getCurrentUser = userMock.getCurrentUser;
service.getAlerts = function(id) {
var deferred = $q.defer();
userMock.getAlerts(id).then(function(response) {
if (response.hasOwnProperty('data')) {
// Convert 'he' to 'Chuck Norris'
angular.forEach(response.data, function(alert) {
if (alert.message) {
alert.message = alert.message.replace(/he/gi, "Chuck Norris");
}
});
deferred.resolve(response.data);
} else {
deferred.reject('DATA ERROR');
}
}, function(e) {
deferred.reject(e);
});
return deferred.promise;
};
service.deleteAlert = function(userId, id) {
var deferred = $q.defer();
userMock.deleteAlert(userId, id).then(function(response) {
deferred.resolve(response.data);
}, function(e) {
deferred.reject('DATA ERROR');
});
return deferred.promise;
};
return service;
};
angular
.module('abp', [])
.service('userMock', userMock)
.service('userService', userService)
.controller('MyLivestockController', MyLivestockController);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<div ng-app="abp">
<div data-ng-controller="MyLivestockController as vm">
<div>Alerts</div>
<span data-ng-bind="vm.alertsNotification.isLoading ? 'Updating...' : vm.alertCount"></span>
<div data-ng-repeat="alert in vm.alerts">
{{alert.id}}: {{alert.message}}
<button ng-click="vm.deleteAlert(alert.id)">Delete</button>
</div>
</div>
</div>

Categories