Splitting a controller in 2 different files. Angular - angularjs

I am getting a headache trying to do this, I have a very big controller which I need to split, this controller has 177 lines already so I need 2 controllers. Once I try to split it my app breaks down.
Maybe you could help by giving suggestions on how to start and what I have to evaluate first. I am new to Angular and I thought it would be easier.
'use strict';
angular.module('capilleira.clickAndGambleMobile.controllers')
.controller('LinesController', function($scope, $timeout, $state,
$stateParams, $ionicLoading, $rootScope, LinesFactory, BetSlipFactory) {
$scope.picksCount = false;
var validateSanitizeLineParams = function() {
var lineParamsOk = false;
if (validator.isAlphanumeric($stateParams.customerId) &&
validator.isNumeric($stateParams.familyGameId) &&
validator.isNumeric($stateParams.games) &&
validator.isNumeric($stateParams.top) &&
validator.isNumeric($stateParams.sports) &&
validator.isLength($stateParams.leagues.trim(), 1) &&
validator.isAscii($stateParams.leagues.trim()) &&
validator.isLength($stateParams.periods.trim(), 1) &&
validator.isAscii($stateParams.periods.trim())) {
lineParamsOk = true;
_.each($stateParams.periods.split(','), function(periodId) {
if (!validator.isAlpha(periodId)) {
lineParamsOk = false;
}
});
_.each($stateParams.leagues.split(','), function(leagueId) {
if (!validator.isNumeric(leagueId)) {
lineParamsOk = false;
}
});
}
return lineParamsOk;
};
$scope.lineItems = [];
$rootScope.spinnerTitle = 'Loading lines';
$ionicLoading.show({
templateUrl: 'templates/loaders.html',
scope: $rootScope
});
$scope.doRefresh = function() {
if (validateSanitizeLineParams()) {
LinesFactory.getLines($stateParams).then(function(linesPerLeague) {
_.each(linesPerLeague, function(linesPerParent) {
_.each(linesPerParent, function(lines) {
_.each(lines, function(line) {
_.each(line.rows, function(row) {
if (!row.noSpread) {
line.displaySpreadButton = true;
}
if (!row.noTotal) {
line.displayTotalButton = true;
}
if (!row.noMoneyLine) {
line.displayMoneyLineButton = true;
}
});
if (line.displaySpreadButton) {
line.displaySpread = true;
} else if (line.displayTotalButton) {
line.displayTotal = true;
} else if (line.displayMoneyLineButton) {
line.displayMoneyLine = true;
}
});
});
});
$scope.lineItems = linesPerLeague;
if (!$scope.lineItems[0].length) {
$state.go('app.noLines');
}
$ionicLoading.hide();
$scope.addLineSelections();
}, function(err) {
console.log(err);
$rootScope.spinnerTitle = 'Wrong Params';
$ionicLoading.show({
templateUrl: 'templates/loaders.html',
scope: $rootScope
});
$timeout(function() {
$ionicLoading.hide();
$state.go('app.login');
}, 1500);
});
}else {
$rootScope.spinnerTitle = 'Wrong Params';
$ionicLoading.show({
templateUrl: 'templates/loaders.html',
scope: $rootScope
});
$timeout(function() {
$ionicLoading.hide();
$state.go('app.login');
}, 1500);
}
$scope.$broadcast('scroll.refreshComplete');
};
$scope.doRefresh();
$scope.showLine = function(lineType, line) {
switch (lineType) {
case 'spread':
line.displayTotal = false;
line.displayMoneyLine = false;
line.displaySpread = false;
$timeout(function() {
line.displaySpread = true;
}, 50);
break;
case 'total':
line.displaySpread = false;
line.displayMoneyLine = false;
line.displayTotal = false;
$timeout(function() {
line.displayTotal = true;
}, 50);
break;
case 'moneyline':
line.displaySpread = false;
line.displayTotal = false;
line.displayMoneyLine = false;
$timeout(function() {
line.displayMoneyLine = true;
}, 50);
break;
}
};
$scope.addLineToBetSlip = function(line, row, type) {
var spreadSelected = (row.spreadSelected && type === 'spread'),
totalSelected = (row.totalSelected && type === 'total'),
moneyLineSelected = (row.moneyLineSelected && type === 'moneyline');
if (spreadSelected || totalSelected || moneyLineSelected) {
BetSlipFactory.remove(line, row, type);
}else {
BetSlipFactory.add(line, row, type);
}
$scope.picksCount = !$scope.picksCount;
};
$scope.addLineSelections = function() {
BetSlipFactory.getBetSlip().then(function(betSlip) {
var flattenLines = _.flatten($scope.lineItems),
lineFound, row;
_.each(betSlip, function(slip) {
lineFound = _.find(flattenLines, function(line) {
return line.gameId === slip.gameId &&
line.part === slip.part &&
line.lineTypeName === slip.lineTypeName;
});
if (lineFound) {
row = _.find(lineFound.rows, function(row) {
return row.nss === slip.nss;
});
if (row) {
switch (slip.type) {
case 'spread':
row.spreadSelected = true;
break;
case 'total':
row.totalSelected = true;
break;
case 'moneyline':
row.moneyLineSelected = true;
break;
}
}
}
});
});
};
});

This works as expected.
var app = angular.module('plunker', []);
var FatCtrl1 = function($scope){
$scope.stuff1 = this.hello;
};
var FatCtrl2 = function($scope){
$scope.stuff2 = "World";
};
app.controller('FatCtrl', function($scope) {
this.hello = "Hello";
FatCtrl1.apply(this, arguments);
FatCtrl2.apply(this, arguments);
});
Beware of closures. Variables within FatCtrl are not available in the partitions. 'this' is used to share data.

Related

Unable to get value from AngularJS Scope

I have an existing project in AngularJS. There is an HTML page with client address. Its markup is:
<div class="text-left m-t-lg">
<h5>
Address
</h5>
<address>
<div ng-show="customerInfo.companyName != ''"><small>{{customerInfo.companyName}}</small><br /></div>
<div ng-show="customerInfo.customerName != ''"><small>{{customerInfo.customerName}}</small><br /></div>
<div ng-show="customerInfo.address != ''"><small>{{customerInfo.address}}</small><br /></div>
<div ng-show="customerInfo.email != ''"><small>{{customerInfo.email}}</small></div>
</address>
</div>
The directive:
app.directive('addressHeader', function () {
return {
scope: {
addressHeaderInfo: '=info'
},
templateUrl: 'address/addressHeader.html',
controller: 'addressHeaderController',
controllerAs: 'ahc'
};
});
My issue is In addressHeaderController.js I don't see addressHeaderInfo or info or customerInfo object. I need to update this object. Where is this object initialized from? I don't know much about AngularJS.
Controller:
app.controller('addressHeaderController', ['$http', 'APIService', '$scope', '$stateParams', '$sessionStorage', '$translate', '$state', '$rootScope', '$timeout', '$locale', 'tmhDynamicLocale',
function ($http, APIService, $scope, $stateParams, $sessionStorage, $translate, $state, $rootScope, $timeout, $locale, tmhDynamicLocale) {
var ctl = this;
$scope.followingAddress = false;
$scope.followData = {};
$scope.issueDisplay = '';
$scope.showResend = true;
$scope.showLoyaltyColumn = $sessionStorage.userObject.clientInfo.showLoyaltyColumnOnSurveyDetail;
ctl.isOpen = false;
ctl.dateOptions = { showWeeks: false };
$scope.businessUnits = null;
$scope.targetDealership = null;
$scope.realignComment = null;
$scope.$watch('addressHeaderInfo', function () {
debugger;
//Where is $scope.addressHeaderInfo coming from?
if (typeof ($scope.addressHeaderInfo) != 'undefined') {
//Some operations here. Not related to assigning anything to $scope.
}
});
function getDepartmentData() {
//No assignment here as well.
}
$scope.resendData = function () {
if ($sessionStorage.clientObject.requiresResendJustification) {
$('#resendJustificationModal').modal('show');
}
else {
var resendData = {};
resendData.recordId = $scope.addressHeaderInfo.addressID;
resendData.statusId = 24;
APIService.postData(resendData, 'Address/UpdateResendStatus')
.then(function (data) {
if (data.status == 200) {
$rootScope.$broadcast('resendRequest');
}
else {
toastr["error"]('Error');
}
});
}
}
$scope.nextAddress = function () {
$rootScope.$broadcast('addressNavigation', $scope.AddressList[$scope.recordNumber]);
$scope.recordNumber = $scope.recordNumber + 1;
}
$scope.previousAddress = function () {
$rootScope.$broadcast('addressNavigation', $scope.AddressList[$scope.recordNumber-2]);
$scope.recordNumber = $scope.recordNumber - 1;
}
$scope.followAddress = function () {
APIService.postData($scope.addressHeaderInfo, 'Address/follow')
.then(function (data) {
if (data.status == 200) {
toastr["success"]($translate.instant('AddressFollowedSaved'));
$scope.followData = data.data;
$scope.followingAddress = true;
}
else {
toastr["error"]($translate.instant('AddressFollowedErrored'));
}
})
}
$scope.unfollowAddress = function () {
APIService.deleteData('Address/follow/' + $scope.followData.AddressFavoriteId)
.then(function (data) {
if (data.status == 200) {
toastr["success"]($translate.instant('AddressUnfollowedSaved'));
$scope.followingAddress = false;
}
else if (data.status == 500) {
toastr["error"]($translate.instant('AddressUnfollowedErrored'));
}
});
}
$scope.AddressReminder = function () {
$('#setReminderPopup').modal('show');
}
$scope.saveReminder = function () {
$scope.followData.notificationDate = $scope.followData.displayDate;
APIService.postData($scope.followData, 'Address/follow/reminder')
.then(function (data) {
if (data.status == 200) {
toastr["success"]($translate.instant('AddressReminderSaved'));
$('#setReminderPopup').modal('hide');
}
else {
toastr["error"]($translate.instant('AddressReminderErrored'));
}
})
}
$scope.realignAddress = function () {
if ($scope.addressHeaderInfo) {
if (!$scope.businessUnits) {
getBusinessUnits();
}
var bu = $scope.addressHeaderInfo.businessUnit;
if (bu) {
bu.realignDisplayName = bu.name + ', ' + bu.shippingCity + ', ' + bu.suppliedBusinessUnitNumber;
}
$scope.realignComment = null;
$('#realignPopup').modal('show');
}
}
$scope.saveRealignRequest = function () {
var realignedAddress = $scope.addressHeaderInfo;
var realignData = {
AddressId: $scope.addressHeaderInfo.AddressID,
businessUnitId: $scope.targetDealership.businessUnitID,
notes: $scope.realignComment
};
APIService.postData(realignData, 'Address/requestRealignment')
.then(function (data) {
if (data.status == 200) {
toastr["success"]($translate.instant('AddressRealignRequestSaved'));
$('#realignPopup').modal('hide');
realignedAddress.realignmentStatus = 'Pending'; // cause Realign button to disappear and "Realignment is pending" message to show
} else {
toastr["error"]($translate.instant('AddressRealignRequestErrored'));
}
});
}
$scope.$on('advanceToNextIssue', function (event, data) {
if ($scope.AddressList && ($scope.recordNumber < $scope.AddressList.length)) {
$scope.nextAddress();
}
});
}]);

Directive's scope value is not getting updated when outer scope value changes in angularjs

My html code is as follows.
<div class="panel-heading">
Select areas to be visited by the operator
<multiselect ng-model="selection" options="areanames" show-search="true"></multiselect>
</div>
My application's controller code is as follows. The function getArea is being called when a user inputs some details in the form (not included here).
this.getArea = function(){
$scope.areanames = [];
$http({
method: "GET",
url: "http://xx.xx.xx.xx/abc",
params:{city:$scope.city,circle:$scope.circle}
}).then(function(success){
for (i = 0; i < success.data.length; i++)
$scope.areanames.push(success.data[i].area);
},function(error){
console.log('error ' + JSON.stringify(error));
});
}
The directive multiselect is written as follows.
multiselect.directive('multiselect', ['$filter', '$document', '$log', function ($filter, $document, $log) {
return {
restrict: 'AE',
scope: {
options: '=',
displayProp: '#',
idProp: '#',
searchLimit: '=?',
selectionLimit: '=?',
showSelectAll: '=?',
showUnselectAll: '=?',
showSearch: '=?',
searchFilter: '=?',
disabled: '=?ngDisabled'
},
replace:true,
require: 'ngModel',
templateUrl: 'multiselect.html',
link: function ($scope, $element, $attrs, $ngModelCtrl) {
$scope.selectionLimit = $scope.selectionLimit || 0;
$scope.searchLimit = $scope.searchLimit || 25;
$scope.searchFilter = '';
if (typeof $scope.options !== 'function') {
$scope.resolvedOptions = $scope.options;
}
if (typeof $attrs.disabled != 'undefined') {
$scope.disabled = true;
}
$scope.toggleDropdown = function () {
console.log('toggleDown');
$scope.open = !$scope.open;
};
var closeHandler = function (event) {
console.log('closeHandler');
if (!$element[0].contains(event.target)) {
$scope.$apply(function () {
$scope.open = false;
});
}
};
$document.on('click', closeHandler);
var updateSelectionLists = function () {
console.log('updateSelectionList');
if (!$ngModelCtrl.$viewValue) {
if ($scope.selectedOptions) {
$scope.selectedOptions = [];
}
$scope.unselectedOptions = $scope.resolvedOptions.slice(); // Take a copy
} else {
$scope.selectedOptions = $scope.resolvedOptions.filter(function (el) {
var id = $scope.getId(el);
for (var i = 0; i < $ngModelCtrl.$viewValue.length; i++) {
var selectedId = $scope.getId($ngModelCtrl.$viewValue[i]);
if (id === selectedId) {
return true;
}
}
return false;
});
$scope.unselectedOptions = $scope.resolvedOptions.filter(function (el) {
return $scope.selectedOptions.indexOf(el) < 0;
});
}
};
$ngModelCtrl.$render = function () {
console.log('render called');
updateSelectionLists();
};
$ngModelCtrl.$viewChangeListeners.push(function () {
console.log('viewChangeListener');
updateSelectionLists();
});
$ngModelCtrl.$isEmpty = function (value) {
console.log('isEmpty');
if (value) {
return (value.length === 0);
} else {
return true;
}
};
var watcher = $scope.$watch('selectedOptions', function () {
$ngModelCtrl.$setViewValue(angular.copy($scope.selectedOptions));
}, true);
$scope.$on('$destroy', function () {
console.log('destroy');
$document.off('click', closeHandler);
if (watcher) {
watcher(); // Clean watcher
}
});
$scope.getButtonText = function () {
console.log('getButtonText');
if ($scope.selectedOptions && $scope.selectedOptions.length === 1) {
return $scope.getDisplay($scope.selectedOptions[0]);
}
if ($scope.selectedOptions && $scope.selectedOptions.length > 1) {
var totalSelected;
totalSelected = angular.isDefined($scope.selectedOptions) ? $scope.selectedOptions.length : 0;
if (totalSelected === 0) {
return 'Select';
} else {
return totalSelected + ' ' + 'selected';
}
} else {
return 'Select';
}
};
$scope.selectAll = function () {
console.log('selectAll');
$scope.selectedOptions = $scope.resolvedOptions;
$scope.unselectedOptions = [];
};
$scope.unselectAll = function () {
console.log('unSelectAll');
$scope.selectedOptions = [];
$scope.unselectedOptions = $scope.resolvedOptions;
};
$scope.toggleItem = function (item) {
console.log('toggleItem');
if (typeof $scope.selectedOptions === 'undefined') {
$scope.selectedOptions = [];
}
var selectedIndex = $scope.selectedOptions.indexOf(item);
var currentlySelected = (selectedIndex !== -1);
if (currentlySelected) {
$scope.unselectedOptions.push($scope.selectedOptions[selectedIndex]);
$scope.selectedOptions.splice(selectedIndex, 1);
} else if (!currentlySelected && ($scope.selectionLimit === 0 || $scope.selectedOptions.length < $scope.selectionLimit)) {
var unselectedIndex = $scope.unselectedOptions.indexOf(item);
$scope.unselectedOptions.splice(unselectedIndex, 1);
$scope.selectedOptions.push(item);
}
};
$scope.getId = function (item) {
console.log('getID');
if (angular.isString(item)) {
return item;
} else if (angular.isObject(item)) {
if ($scope.idProp) {
return multiselect.getRecursiveProperty(item, $scope.idProp);
} else {
$log.error('Multiselect: when using objects as model, a idProp value is mandatory.');
return '';
}
} else {
return item;
}
};
$scope.getDisplay = function (item) {
console.log('getDisplay');
if (angular.isString(item)) {
return item;
} else if (angular.isObject(item)) {
if ($scope.displayProp) {
return multiselect.getRecursiveProperty(item, $scope.displayProp);
} else {
$log.error('Multiselect: when using objects as model, a displayProp value is mandatory.');
return '';
}
} else {
return item;
}
};
$scope.isSelected = function (item) {
console.log('isSelected');
if (!$scope.selectedOptions) {
return false;
}
var itemId = $scope.getId(item);
for (var i = 0; i < $scope.selectedOptions.length; i++) {
var selectedElement = $scope.selectedOptions[i];
if ($scope.getId(selectedElement) === itemId) {
return true;
}
}
return false;
};
$scope.updateOptions = function () {
console.log('updateOptions');
if (typeof $scope.options === 'function') {
$scope.options().then(function (resolvedOptions) {
$scope.resolvedOptions = resolvedOptions;
updateSelectionLists();
});
}
};
// This search function is optimized to take into account the search limit.
// Using angular limitTo filter is not efficient for big lists, because it still runs the search for
// all elements, even if the limit is reached
$scope.search = function () {
console.log('search');
var counter = 0;
return function (item) {
if (counter > $scope.searchLimit) {
return false;
}
var displayName = $scope.getDisplay(item);
if (displayName) {
var result = displayName.toLowerCase().indexOf($scope.searchFilter.toLowerCase()) > -1;
if (result) {
counter++;
}
return result;
}
}
};
}
};
}]);
When areanames is getting updated asynchronously its values are not getting displayed in multiselect. The inner scope's options value is becoming undefined though I am using '=' with same attribute name i.e., options in the html code.

Cordova/Ionic httpd server plugin - url not visible

i have a problem with Angular controller in my Ionic/Cordova project.
Can someone explain me why url which i get in line 25: $scope.serverURL=url;
isn't visible in line 63 alert($scope.serverURL); (it return null)?
Here is my controller:
var app = angular.module('iremotee');
app.controller('StreamingController', function(ConnectSdkService, $scope, $rootScope, $state, Camera) {
var options = {
quality: 100,
destinationType: 0,
sourceType: 0,
mediaType: 2
};
$scope.currentFile = null;
$scope.httpd = null;
$scope.serverURL = null;
alert($scope.serverURL + "!!!");
$scope.createHttpd = function() {
$scope.httpd = (cordova && cordova.plugins && cordova.plugins.CorHttpd) ? cordova.plugins.CorHttpd : null;
};
$scope.startMediaServer = function() {
if ($scope.httpd) {
// before start, check whether its up or not
$scope.httpd.getURL(function(url) {
if (url.length > 0) {
$scope.serverURL = url;
alert($scope.serverURL);
} else {
$scope.httpd.startServer({
'www_root': '/',
'port': 8080,
'localhost_only': false
}, function(url) {
$scope.serverURL = url;
alert($scope.serverURL);
}, function(error) {});
}
});
} else {}
};
$scope.stopServer = function() {
if ($scope.httpd) {
$scope.httpd.stopServer(function() {}, function(error) {});
}
};
$scope.getMedia = function() {
$state.go('mainmenu');
};
ionic.Platform.ready(function() {
$scope.createHttpd();
$scope.startMediaServer();
});
$scope.getFile = function() {
alert($scope.serverURL);
Camera.getFromMemory(options).then(function(URI) {
if (URI.indexOf("file://") == -1) {
URI = "file://" + URI;
}
window.resolveLocalFileSystemURL(URI, function(fileEntry) {
var URI = fileEntry.toURL();
var str = URI;
str = str.replace("file:///storage/emulated/0/", "/sdcard/");
str = str.replace("file:///storage/emulated/0/", "/sdcard1/");
str = str.replace("file:///storage", "");
Camera.currentURI = str;
alert(Camera.currentURI);
$scope.currentFile = Camera.currentURI;
}); //resolveLocalFileSystemURL-END
}, function(err) {
alert(err);
}); //getFromMemory-END
}; //getFile-END
$scope.$on('$destroy', function() {
$scope.stopServer();
});
});

Angularjs expression is not working

I tried to use the angular expression below in html 5 but it is not working.
index.html
* * < !DOCTYPE html >
< html >
< script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js" > < /script> < script src = "blockuijs.js" > < /script> < body >
< div ng - app = "icebreakerapp" >
< p > My first expression: {
{
5 + 5
}
} </p> </div> < script >
var module = angular.module('icebreakerapp', ['blockUI']); < /script> < /body> < /html>**
blockuijs.js
(function(angular) {
var blkUI = angular.module('blockUI', []);
blkUI.config(["$provide", "$httpProvider", function($provide, $httpProvider) {
$provide.decorator('$exceptionHandler', ['$delegate', '$injector', function($delegate, $injector) {
var blockUI, blockUIConfig;
return function(exception, cause) {
blockUIConfig = blockUIConfig || $injector.get('blockUIConfig');
if (blockUIConfig.resetOnException) {
blockUI = blockUI || $injector.get('blockUI');
blockUI.instances.reset();
}
$delegate(exception, cause);
};
}]);
$httpProvider.interceptors.push('blockUIHttpInterceptor');
}]);
blkUI.run(["$document", "blockUIConfig", "$templateCache", function($document, blockUIConfig, $templateCache) {
if (blockUIConfig.autoInjectBodyBlock) {
$document.find('body').attr('block-ui', 'main');
}
if (blockUIConfig.template) {
blockUIConfig.templateUrl = '$$block-ui-template$$';
$templateCache.put(blockUIConfig.templateUrl, blockUIConfig.template);
}
}]);
blkUI.directive('blockUiContainer', ["blockUIConfig", "blockUiContainerLinkFn", function(blockUIConfig, blockUiContainerLinkFn) {
return {
scope: true,
restrict: 'A',
templateUrl: blockUIConfig.templateUrl,
compile: function($element) {
return blockUiContainerLinkFn;
}
};
}]).factory('blockUiContainerLinkFn', ["blockUI", "blockUIUtils", function(blockUI, blockUIUtils) {
return function($scope, $element, $attrs) {
var srvInstance = $element.inheritedData('block-ui');
if (!srvInstance) {
throw new Error('No parent block-ui service instance located.');
}
$scope.state = srvInstance.state(); //
};
}]);
blkUI.directive('blockUi', ["blockUiCompileFn", function(blockUiCompileFn) {
return {
scope: true,
restrict: 'A',
compile: blockUiCompileFn
};
}]).factory('blockUiCompileFn', ["blockUiPreLinkFn", function(blockUiPreLinkFn) {
return function($element, $attrs) {
$element.append('<div block-ui-container class="block-ui-container"></div>');
return {
pre: blockUiPreLinkFn
};
};
}]).factory('blockUiPreLinkFn', ["blockUI", "blockUIUtils", "blockUIConfig", function(blockUI, blockUIUtils, blockUIConfig) {
return function($scope, $element, $attrs) {
if (!$element.hasClass('block-ui')) {
$element.addClass(blockUIConfig.cssClass);
}
$attrs.$observe('blockUiMessageClass', function(value) {
$scope.$_blockUiMessageClass = value;
});
var instanceId = $attrs.blockUi || '_' + $scope.$id;
var srvInstance = blockUI.instances.get(instanceId);
if (instanceId === 'main') {
var fn = $scope.$on('$viewContentLoaded', function($event) {
fn();
$scope.$on('$locationChangeStart', function(event) {
if (srvInstance.state().blockCount > 0) {
event.preventDefault();
}
});
});
} else {
var parentInstance = $element.inheritedData('block-ui');
if (parentInstance) {
srvInstance._parent = parentInstance;
}
}
$scope.$on('$destroy', function() {
srvInstance.release();
});
srvInstance.addRef();
$scope.$_blockUiState = srvInstance.state();
$scope.$watch('$_blockUiState.blocking', function(value) {
$element.attr('aria-busy', !!value);
$element.toggleClass('block-ui-visible', !!value);
});
$scope.$watch('$_blockUiState.blockCount > 0', function(value) {
$element.toggleClass('block-ui-active', !!value);
});
var pattern = $attrs.blockUiPattern;
if (pattern) {
var regExp = blockUIUtils.buildRegExp(pattern);
srvInstance.pattern(regExp);
}
$element.data('block-ui', srvInstance);
};
}]);
blkUI.constant('blockUIConfig', {
templateUrl: 'angular-block-ui/angular-block-ui.ng.html',
delay: 250,
message: "Loading ...",
autoBlock: true,
resetOnException: true,
requestFilter: angular.noop,
autoInjectBodyBlock: true,
cssClass: 'block-ui block-ui-anim-fade'
});
blkUI.factory('blockUIHttpInterceptor', ["$q", "$injector", "blockUIConfig", function($q, $injector, blockUIConfig) {
var blockUI;
function injectBlockUI() {
blockUI = blockUI || $injector.get('blockUI');
}
function stopBlockUI(config) {
if (blockUIConfig.autoBlock && !config.$_noBlock && config.$_blocks) {
injectBlockUI();
config.$_blocks.stop();
}
}
function error(rejection) {
stopBlockUI(rejection.config);
return $q.reject(rejection);
}
return {
request: function(config) {
if (blockUIConfig.autoBlock) {
if (blockUIConfig.requestFilter(config) === false) {
config.$_noBlock = true;
} else {
injectBlockUI();
config.$_blocks = blockUI.instances.locate(config);
config.$_blocks.start();
}
}
return config;
},
requestError: error,
response: function(response) {
stopBlockUI(response.config);
return response;
},
responseError: error
};
}]);
blkUI.factory('blockUI', ["blockUIConfig", "$timeout", "blockUIUtils", "$document", function(blockUIConfig, $timeout, blockUIUtils, $document) {
var $body = $document.find('body');
function BlockUI(id) {
var self = this;
var state = {
id: id,
blockCount: 0,
message: blockUIConfig.message,
blocking: false
},
startPromise, doneCallbacks = [];
this._refs = 0;
this.start = function(message) {
if (state.blockCount > 0) {
message = message || state.message || blockUIConfig.message;
} else {
message = message || blockUIConfig.message;
}
state.message = message;
state.blockCount++;
var $ae = angular.element($document[0].activeElement);
if ($ae.length && blockUIUtils.isElementInBlockScope($ae, self)) { //
self._restoreFocus = $ae[0];
$timeout(function() {
if (self._restoreFocus) {
self._restoreFocus.blur();
}
});
}
if (!startPromise) {
startPromise = $timeout(function() {
startPromise = null;
state.blocking = true;
}, blockUIConfig.delay);
}
};
this._cancelStartTimeout = function() {
if (startPromise) {
$timeout.cancel(startPromise);
startPromise = null;
}
};
this.stop = function() {
state.blockCount = Math.max(0, --state.blockCount);
if (state.blockCount === 0) {
self.reset(true);
}
};
this.message = function(value) {
state.message = value;
};
this.pattern = function(regexp) {
if (regexp !== undefined) {
self._pattern = regexp;
}
return self._pattern;
};
this.reset = function(executeCallbacks) {
self._cancelStartTimeout();
state.blockCount = 0;
state.blocking = false;
if (self._restoreFocus && (!$document[0].activeElement || $document[0].activeElement === $body[0])) {
self._restoreFocus.focus();
self._restoreFocus = null;
}
try {
if (executeCallbacks) {
angular.forEach(doneCallbacks, function(cb) {
cb();
});
}
} finally {
doneCallbacks.length = 0;
}
};
this.done = function(fn) {
doneCallbacks.push(fn);
};
this.state = function() {
return state;
};
this.addRef = function() {
self._refs += 1;
};
this.release = function() {
if (--self._refs <= 0) {
mainBlock.instances._destroy(self);
}
};
}
var instances = [];
instances.get = function(id) {
var instance = instances[id];
if (!instance) {
instance = instances[id] = new BlockUI(id);
instances.push(instance);
}
return instance;
};
instances._destroy = function(idOrInstance) {
if (angular.isString(idOrInstance)) {
idOrInstance = instances[idOrInstance];
}
if (idOrInstance) {
idOrInstance.reset();
delete instances[idOrInstance.state().id];
var i = instances.length;
while (--i) {
if (instances[i] === idOrInstance) {
instances.splice(i, 1);
break;
}
}
}
};
instances.locate = function(request) {
var result = [];
blockUIUtils.forEachFnHook(result, 'start');
blockUIUtils.forEachFnHook(result, 'stop');
var i = instances.length;
while (i--) {
var instance = instances[i];
var pattern = instance._pattern;
if (pattern && pattern.test(request.url)) {
result.push(instance);
}
}
if (result.length === 0) {
result.push(mainBlock);
}
return result;
};
blockUIUtils.forEachFnHook(instances, 'reset');
var mainBlock = instances.get('main');
mainBlock.addRef();
mainBlock.instances = instances;
return mainBlock;
}]);
blkUI.factory('blockUIUtils', function() {
var $ = angular.element;
var utils = {
buildRegExp: function(pattern) {
var match = pattern.match(/^\/(.*)\/([gim]*)$/),
regExp;
if (match) {
regExp = new RegExp(match[1], match[2]);
} else {
throw Error('Incorrect regular expression format: ' + pattern);
}
return regExp;
},
forEachFn: function(arr, fnName, args) {
var i = arr.length;
while (i--) {
var t = arr[i];
t[fnName].apply(t, args);
}
},
forEachFnHook: function(arr, fnName) {
arr[fnName] = function() {
utils.forEachFn(this, fnName, arguments);
}
},
isElementInBlockScope: function($element, blockScope) {
var c = $element.inheritedData('block-ui');
while (c) {
if (c === blockScope) {
return true;
}
c = c._parent;
}
return false;
},
findElement: function($element, predicateFn, traverse) {
var ret = null;
if (predicateFn($element)) {
ret = $element;
} else {
var $elements;
if (traverse) {
$elements = $element.parent();
} else {
$elements = $element.children();
}
var i = $elements.length;
while (!ret && i--) {
ret = utils.findElement($($elements[i]), predicateFn, traverse);
}
}
return ret;
}
};
return utils;
});
angular.module('blockUI').run(['$templateCache', function($templateCache) {
$templateCache.put('angular-block-ui/angular-block-ui.ng.html', '<div class=\"block-ui-overlay\"></div><div class=\"block-ui-message-container\" aria-live=\"assertive\" aria-atomic=\"true\"><div class=\"block-ui-message loading_spinnerlatest\" ng-class=\"$_blockUiMessageClass\">{{ state.message }}</div></div>');
}]);
})(angular); //
It is giving the output as "My first expression:{{ 5+5}}".But expectation is "My first expression:10"
Note: If I remove dependency modules in (angular.module) it is working.But I need those dependency modules
for further development
Are you seeing any error in console? Maybe some of your module dependencies are not resolved.
Check this snippet:
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="icebreakerapp">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
<script>
var module = angular.module('icebreakerapp', []);
</script>

Script error in angular-file-upload.js

I get 'Script error in the below js' file .This is the file downloaded using bower install from cloudinary-angular from git hub. Whats the error here?
angular-file-upload.js
/**!
* AngularJS file upload/drop directive with http post and progress
* #author Danial
* #version 1.6.6
*/
(function() {
var angularFileUpload = angular.module('angularFileUpload', []);
angularFileUpload.service('$upload', ['$http', '$q', '$timeout', function($http, $q, $timeout) {
function sendHttp(config) {
config.method = config.method || 'POST';
config.headers = config.headers || {};
config.transformRequest = config.transformRequest || function(data, headersGetter) {
if (window.ArrayBuffer && data instanceof window.ArrayBuffer) {
return data;
}
return $http.defaults.transformRequest[0](data, headersGetter);
};
var deferred = $q.defer();
if (window.XMLHttpRequest.__isShim) {
config.headers['__setXHR_'] = function() {
return function(xhr) {
if (!xhr) return;
config.__XHR = xhr;
config.xhrFn && config.xhrFn(xhr);
xhr.upload.addEventListener('progress', function(e) {
deferred.notify(e);
}, false);
//fix for firefox not firing upload progress end, also IE8-9
xhr.upload.addEventListener('load', function(e) {
if (e.lengthComputable) {
deferred.notify(e);
}
}, false);
};
};
}
$http(config).then(function(r){deferred.resolve(r)}, function(e){deferred.reject(e)}, function(n){deferred.notify(n)});
var promise = deferred.promise;
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error = function(fn) {
promise.then(null, function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.progress = function(fn) {
promise.then(null, null, function(update) {
fn(update);
});
return promise;
};
promise.abort = function() {
if (config.__XHR) {
$timeout(function() {
config.__XHR.abort();
});
}
return promise;
};
promise.xhr = function(fn) {
config.xhrFn = (function(origXhrFn) {
return function() {
origXhrFn && origXhrFn.apply(promise, arguments);
fn.apply(promise, arguments);
}
})(config.xhrFn);
return promise;
};
return promise;
}
this.upload = function(config) {
config.headers = config.headers || {};
config.headers['Content-Type'] = undefined;
config.transformRequest = config.transformRequest || $http.defaults.transformRequest;
var formData = new FormData();
var origTransformRequest = config.transformRequest;
var origData = config.data;
config.transformRequest = function(formData, headerGetter) {
if (origData) {
if (config.formDataAppender) {
for (var key in origData) {
var val = origData[key];
config.formDataAppender(formData, key, val);
}
} else {
for (var key in origData) {
var val = origData[key];
if (typeof origTransformRequest == 'function') {
val = origTransformRequest(val, headerGetter);
} else {
for (var i = 0; i < origTransformRequest.length; i++) {
var transformFn = origTransformRequest[i];
if (typeof transformFn == 'function') {
val = transformFn(val, headerGetter);
}
}
}
formData.append(key, val);
}
}
}
if (config.file != null) {
var fileFormName = config.fileFormDataName || 'file';
if (Object.prototype.toString.call(config.file) === '[object Array]') {
var isFileFormNameString = Object.prototype.toString.call(fileFormName) === '[object String]';
for (var i = 0; i < config.file.length; i++) {
formData.append(isFileFormNameString ? fileFormName : fileFormName[i], config.file[i],
(config.fileName && config.fileName[i]) || config.file[i].name);
}
} else {
formData.append(fileFormName, config.file, config.fileName || config.file.name);
}
}
return formData;
};
config.data = formData;
return sendHttp(config);
};
this.http = function(config) {
return sendHttp(config);
}
}]);
angularFileUpload.directive('ngFileSelect', [ '$parse', '$timeout', function($parse, $timeout) {
return function(scope, elem, attr) {
var fn = $parse(attr['ngFileSelect']);
if (elem[0].tagName.toLowerCase() !== 'input' || (elem.attr('type') && elem.attr('type').toLowerCase()) !== 'file') {
var fileElem = angular.element('<input type="file">')
for (var i = 0; i < elem[0].attributes.length; i++) {
fileElem.attr(elem[0].attributes[i].name, elem[0].attributes[i].value);
}
if (elem.attr("data-multiple")) fileElem.attr("multiple", "true");
fileElem.css("top", 0).css("bottom", 0).css("left", 0).css("right", 0).css("width", "100%").
css("opacity", 0).css("position", "absolute").css('filter', 'alpha(opacity=0)');
elem.append(fileElem);
if (fileElem.parent()[0] != elem[0]) {
//fix #298
elem.wrap('<span>');
elem.css("z-index", "-1000")
elem.parent().append(fileElem);
elem = elem.parent();
}
if (elem.css("position") === '' || elem.css("position") === 'static') {
elem.css("position", "relative");
}
elem = fileElem;
}
elem.bind('change', function(evt) {
var files = [], fileList, i;
fileList = evt.__files_ || evt.target.files;
if (fileList != null) {
for (i = 0; i < fileList.length; i++) {
files.push(fileList.item(i));
}
}
$timeout(function() {
fn(scope, {
$files : files,
$event : evt
});
});
});
// removed this since it was confusing if the user click on browse and then cancel #181
// elem.bind('click', function(){
// this.value = null;
// });
// removed because of #253 bug
// touch screens
// if (('ontouchstart' in window) ||
// (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0)) {
// elem.bind('touchend', function(e) {
// e.preventDefault();
// e.target.click();
// });
// }
};
} ]);
angularFileUpload.directive('ngFileDropAvailable', [ '$parse', '$timeout', function($parse, $timeout) {
return function(scope, elem, attr) {
if ('draggable' in document.createElement('span')) {
var fn = $parse(attr['ngFileDropAvailable']);
$timeout(function() {
fn(scope);
});
}
};
} ]);
angularFileUpload.directive('ngFileDrop', [ '$parse', '$timeout', '$location', function($parse, $timeout, $location) {
return function(scope, elem, attr) {
if ('draggable' in document.createElement('span')) {
var leaveTimeout = null;
elem[0].addEventListener("dragover", function(evt) {
evt.preventDefault();
$timeout.cancel(leaveTimeout);
if (!elem[0].__drag_over_class_) {
if (attr['ngFileDragOverClass'] && attr['ngFileDragOverClass'].search(/\) *$/) > -1) {
dragOverClassFn = $parse(attr['ngFileDragOverClass']);
var dragOverClass = dragOverClassFn(scope, {
$event : evt
});
elem[0].__drag_over_class_ = dragOverClass;
} else {
elem[0].__drag_over_class_ = attr['ngFileDragOverClass'] || "dragover";
}
}
elem.addClass(elem[0].__drag_over_class_);
}, false);
elem[0].addEventListener("dragenter", function(evt) {
evt.preventDefault();
}, false);
elem[0].addEventListener("dragleave", function(evt) {
leaveTimeout = $timeout(function() {
elem.removeClass(elem[0].__drag_over_class_);
elem[0].__drag_over_class_ = null;
}, attr['ngFileDragOverDelay'] || 1);
}, false);
var fn = $parse(attr['ngFileDrop']);
elem[0].addEventListener("drop", function(evt) {
evt.preventDefault();
elem.removeClass(elem[0].__drag_over_class_);
elem[0].__drag_over_class_ = null;
extractFiles(evt, function(files) {
fn(scope, {
$files : files,
$event : evt
});
});
}, false);
function isASCII(str) {
return /^[\000-\177]*$/.test(str);
}
function extractFiles(evt, callback) {
var files = [], items = evt.dataTransfer.items;
if (items && items.length > 0 && items[0].webkitGetAsEntry && $location.protocol() != 'file' &&
items[0].webkitGetAsEntry().isDirectory) {
for (var i = 0; i < items.length; i++) {
var entry = items[i].webkitGetAsEntry();
if (entry != null) {
//fix for chrome bug https://code.google.com/p/chromium/issues/detail?id=149735
if (isASCII(entry.name)) {
traverseFileTree(files, entry);
} else if (!items[i].webkitGetAsEntry().isDirectory) {
files.push(items[i].getAsFile());
}
}
}
} else {
var fileList = evt.dataTransfer.files;
if (fileList != null) {
for (var i = 0; i < fileList.length; i++) {
files.push(fileList.item(i));
}
}
}
(function waitForProcess(delay) {
$timeout(function() {
if (!processing) {
callback(files);
} else {
waitForProcess(10);
}
}, delay || 0)
})();
}
var processing = 0;
function traverseFileTree(files, entry, path) {
if (entry != null) {
if (entry.isDirectory) {
var dirReader = entry.createReader();
processing++;
dirReader.readEntries(function(entries) {
for (var i = 0; i < entries.length; i++) {
traverseFileTree(files, entries[i], (path ? path : "") + entry.name + "/");
}
processing--;
});
} else {
processing++;
entry.file(function(file) {
processing--;
file._relativePath = (path ? path : "") + file.name;
files.push(file);
});
}
}
}
}
};
} ]);
})();
More context is needed to understand the issue here, for example the way/order the files are included in the page. Specifically, you should verify the correct ordering of the JS files, as shown here:
https://github.com/cloudinary/cloudinary_angular/blob/master/samples/photo_album/app/index.html#L21
I just wanted to require '$parse', '$timeout before this module, which are reffered inside this module.

Resources