Cordova/Ionic httpd server plugin - url not visible - angularjs

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();
});
});

Related

Error: $controller:ctrlreg A controller with this name is not registered

I see this error when I press F12 in chrome, but strangely things still work. There seems to be no problems.
The controller with the name 'AccountUpdateViewModel' is not registered.
Here is my js file. Any idea why? The version of angualr I am using is 1.6.0 from nuget(I develop on Visual Studio)
var accountUpdateModule = angular.module('accountUpdate', ['common', 'ngRoute'])
.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$routeProvider.when(Avts.rootPath + 'account/update/step1', { templateUrl: Avts.rootPath + 'Templates/AccountUpdate/Step1.html', controller: 'AccountUpdateStep1ViewModel' });
$routeProvider.when(Avts.rootPath + 'account/update/step2', { templateUrl: Avts.rootPath + 'Templates/AccountUpdate/Step2.html', controller: 'AccountUpdateStep2ViewModel' });
$routeProvider.when(Avts.rootPath + 'account/update/step3', { templateUrl: Avts.rootPath + 'Templates/AccountUpdate/Step3.html', controller: 'AccountUpdateStep3ViewModel' });
$routeProvider.when(Avts.rootPath + 'account/update/confirm', { templateUrl: Avts.rootPath + 'Templates/AccountUpdate/Confirm.html', controller: 'AccountUpdateConfirmViewModel' });
$routeProvider.when(Avts.rootPath + 'account/update/successfullyupdated', { templateUrl: Avts.rootPath + 'Templates/AccountUpdate/Successfull.html', controller: 'AccountUpdateSuccessfullyUpdatedViewModel' });
// 5:40 Sec. If it does not find any of these steps in this little spa silo, then redirect to step1
$routeProvider.otherwise({ redirectTo: Avts.rootPath + 'account/update/step1' });
});
accountUpdateModule.controller("AccountUpdateViewModel", function ($scope, $http, $location, $window, viewModelHelper) {
// Nested ViewModels or sub viewmodels. See Video 138 3:40 Sec
// Things that are set up here in this view model(AccountRegisterViewModel) is bound to the priticular view Register.cshtml.
// see 4:50 Sec
$scope.viewModelHelper = viewModelHelper;
$scope.accountModelStep1 = new Avts.AccountUpdateModelStep1();
$scope.accountModelStep2 = new Avts.AccountUpdateModelStep2();
$scope.accountModelStep3 = new Avts.AccountUpdateModelStep3();
$scope.fetchDataToUpdate = function () {
viewModelHelper.apiGet('api/account/update', null,
function (result) {
$scope.accountModelStep1.Email = result.data.Email;
$scope.accountModelStep1.UserName = result.data.UserName;
$scope.accountModelStep2.FirstName = result.data.FirstName;
$scope.accountModelStep2.LastName = result.data.LastName;
$scope.accountModelStep3.Address = result.data.Address;
$scope.accountModelStep3.City = result.data.City;
$scope.accountModelStep3.State = result.data.State;
$scope.accountModelStep3.PostalCode = result.data.PostalCode;
});
}
$scope.fetchDataToUpdate();
//$scope.previous = function () {
// // 6:00 Sec
// $window.history.back();
//}
});
accountUpdateModule.controller("AccountUpdateStep1ViewModel", function ($scope, $http, $location, viewModelHelper, validator) {
viewModelHelper.modelIsValid = true;
viewModelHelper.modelErrors = [];
// No setpup rules for step 1 edit. Just showing Email and userName
//var accountModelStep1Rules = [];
//var setupRules = function () {
// accountModelStep1Rules.push(new validator.PropertyRule("Email", {
// required: {
// message: "Email is required",
// email: { message: "Email is not an email." }
// }
// }));
// accountModelStep1Rules.push(new validator.PropertyRule("Password", {
// required: { message: "Password is required" },
// minLength: { message: "Password must be at least 6 characters", params: 6 }
// }));
//accountModelStep1Rules.push(new validator.PropertyRule("PasswordConfirm", {
// required: { message: "Password confirmation is required" },
// custom: {
// validator: Avts.mustEqual, // See 143, 2:30
// message: "Password do not match",
// params: function () { return $scope.accountModelStep1.Password; } // must be function so it can be obtained on-demand
// }
//}));
//}
//$scope.fetchData = function () {
// viewModelHelper.apiGet('api/account/edit', null,
// function (result) {
// $scope.accountModelStep1.Email = result.data.Email;
// $scope.accountModelStep1.UserName = result.data.UserName;
// });
//}
$scope.step2 = function () {
$location.path(Avts.rootPath + 'account/update/step2');
// Video 144
// Pressing should just do validation and proceed to step 2.
//validator.ValidateModel($scope.accountModelStep1, accountModelStep1Rules);
//viewModelHelper.modelIsValid = $scope.accountModelStep1.isValid;
//viewModelHelper.modelErrors = $scope.accountModelStep1.errors;
//if (viewModelHelper.modelIsValid) {
// viewModelHelper.apiPost('api/account/register/validate1', $scope.accountModelStep1,
// function (result) {
// // See the video 144 3:35 Sec
// $scope.accountModelStep1.Initialized = true;
// $location.path(Avts.rootPath + 'account/edit/step2');
// },
// function (failureResult) {
// $scope.accountModelStep1.errors = failureResult.data;
// viewModelHelper.modelErrors = $scope.accountModelStep1.errors;
// viewModelHelper.modelIsValid = false;
// }
// );
//}
//else
// viewModelHelper.modelErrors = $scope.accountModelStep1.errors;
}
//setupRules();
//$scope.fetchData();
});
accountUpdateModule.controller("AccountUpdateStep2ViewModel", function ($scope, $http, $location, viewModelHelper, validator) {
viewModelHelper.modelIsValid = true;
viewModelHelper.modelErrors = [];
var accountModelStep2Rules = [];
var setupRules = function () {
accountModelStep2Rules.push(new validator.PropertyRule("FirstName", {
required: { message: "First name is required" }
}));
accountModelStep2Rules.push(new validator.PropertyRule("LastName", {
required: { message: "Last name is required" }
}));
}
// Video 146
$scope.step3 = function () {
validator.ValidateModel($scope.accountModelStep2, accountModelStep2Rules);
viewModelHelper.modelIsValid = $scope.accountModelStep2.isValid;
viewModelHelper.modelErrors = $scope.accountModelStep2.errors;
if (viewModelHelper.modelIsValid) {
viewModelHelper.apiPost('api/account/update/validate2', $scope.accountModelStep2,
function (result) {
$scope.accountModelStep2.Initialized = true;
$location.path(Avts.rootPath + 'account/update/step3');
},
function (failureResult) {
$scope.accountModelStep2.errors = failureResult.data;
viewModelHelper.modelErrors = $scope.accountModelStep2.errors;
viewModelHelper.modelIsValid = false;
}
);
}
else
viewModelHelper.modelErrors = $scope.accountModelStep2.errors;
}
$scope.backToStep1 = function () {
$location.path(Avts.rootPath + 'account/update/step1');
}
setupRules();
});
accountUpdateModule.controller("AccountUpdateStep3ViewModel", function ($scope, $http, $location, viewModelHelper, validator) {
if (!$scope.accountModelStep2.Initialized) {
// got to this controller before going through step 2
$location.path(Avts.rootPath + 'account/update/step2');
}
var accountModelStep3Rules = [];
var setupRules = function () {
accountModelStep3Rules.push(new validator.PropertyRule("Address", {
required: { message: "Address is required" }
}));
accountModelStep3Rules.push(new validator.PropertyRule("City", {
required: { message: "City is required" }
}));
accountModelStep3Rules.push(new validator.PropertyRule("State", {
required: { message: "State is required" }
}));
accountModelStep3Rules.push(new validator.PropertyRule("PostalCode", {
required: { message: "Postal code is required" },
pattern: { message: "Postal code is in invalid format", params: /^[1-9][0-9]{5}$/ }
}));
//accountModelStep3Rules.push(new validator.PropertyRule("CreditCard", {
// required: { message: "Credit Card # is required" },
// pattern: { message: "Credit card is in invalid format (16 digits)", params: /^\d{16}$/ }
//}));
//accountModelStep3Rules.push(new validator.PropertyRule("ExpiryDate", {
// required: { message: "Expiration Date is required" },
// pattern: { message: "Expiration Date is in invalid format (MM/YY)", params: /^(0[1-9]|1[0-2])\/[0-9]{2}$/ }
//}));
}
$scope.confirm = function () {
validator.ValidateModel($scope.accountModelStep3, accountModelStep3Rules);
viewModelHelper.modelIsValid = $scope.accountModelStep3.isValid;
viewModelHelper.modelErrors = $scope.accountModelStep3.errors;
if (viewModelHelper.modelIsValid) {
viewModelHelper.apiPost('api/account/update/validate3', $scope.accountModelStep3,
function (result) {
$scope.accountModelStep3.Initialized = true;
$location.path(Avts.rootPath + 'account/update/confirm');
},
function (failureResult) {
$scope.accountModelStep3.errors = failureResult.data;
viewModelHelper.modelErrors = $scope.accountModelStep3.errors;
viewModelHelper.modelIsValid = false;
}
);
}
else
viewModelHelper.modelErrors = $scope.accountModelStep3.errors;
}
$scope.backToStep2 = function () {
$location.path(Avts.rootPath + 'account/update/step2');
}
setupRules();
});
accountUpdateModule.controller("AccountUpdateConfirmViewModel", function ($scope, $http, $location, $window, viewModelHelper) {
if (!$scope.accountModelStep3.Initialized) {
// got to this controller before going through step 3
$location.path(Avts.rootPath + 'account/update/step3');
}
$scope.updateAccount = function () {
// Video 147 2:00 Sec
var accountModel;
accountModel = $.extend(accountModel, $scope.accountModelStep1);
accountModel = $.extend(accountModel, $scope.accountModelStep2);
accountModel = $.extend(accountModel, $scope.accountModelStep3);
viewModelHelper.apiPost('api/account/update', accountModel,
function (result) {
//$location.path(Avts.rootPath);
$location.path(Avts.rootPath + 'account/update/successfullyupdated');
//account/update/successfullyupdateded
//account/update/successfullyupdated
//$window.location.href = Avts.rootPath;
},
function (failureResult) {
$scope.accountModelStep1.errors = failureResult.data;
viewModelHelper.modelErrors = $scope.accountModelStep1.errors;
viewModelHelper.modelIsValid = false;
}
);
}
$scope.backToStep3 = function () {
$location.path(Avts.rootPath + 'account/update/step3');
}
});
//AccountUpdateSuccessfullyUpdatedViewModel
accountUpdateModule.controller("AccountUpdateSuccessfullyUpdatedViewModel", function ($scope, $http, $location, $window, viewModelHelper) {
});
You had 'AccountUpdateViewModel controller. but you didn't registered it in your route.config. if you didn't config means you never use it anywhere.
please remove unwanted model. or register it in the rout config section.
i import the file, in index.html and my problem solved,
<script src=".../AccountUpdateStep1ViewModel.js"></script>

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>

Splitting a controller in 2 different files. Angular

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.

angular and prettyphoto url from blobstorage

Prettyphoto stopped working after I changed the href url to an angular tag: {{something.uri}}
Javascript:
jQuery(".prettyphoto").prettyPhoto({
theme: 'pp_default',
overlay_gallery: false,
social_tools: false,
deeplinking: false,
theme: 'dark_rounded'
});
$("a[rel^='prettyPhoto']").prettyPhoto();
HTML:
<div ng-show="model.fileList" ng-repeat="fileList in model.fileList">
<a ng-href="{{fileList.uri}}" class="prettyphoto">
<img ng-src="{{fileList.uri}}" class="img-thumbnail" width="100" alt="" />
</a>
</div>
Angular scope from blobstorage:
fileList: [
{
parentContainerName: documents
uri: https://xxxxxx.blob.core.windows.net/documents/20140702.jpg
filename: 20140702.jpg
fileLengthKilobytes: 293
}
]
app.factory('storageService',
["$http", "$resource", "$q",
function ($http, $resource, $q) {
//resource to get summaryRoles
var resourceStorageManager = $resource('/api/storageManager/:id', { id: '#id' });
return {
getFileList: function () {
var deferred = $q.defer();
resourceStorageManager.query(, function (data) {
deferred.resolve(data);
}, function (status) {
deferred.reject(status);
}
);
return deferred.promise;
}
};
}]);
app.controller('startController', ['$scope', '$http', '$timeout', '$upload', 'storageService', 'settings',
function startController($scope, $http, $timeout, $upload, storageService, settings, profileRepository, notificationFactory, $q) {
$http.defaults.headers.common = { 'RequestVerificationToken': $scope.__RequestVerificationToken };
$scope.model = {};
$scope.model.fileList = null;
$scope.model.roundProgressData = {
label: 0,
percentage: 0.0
};
$scope.$on("pic_profileone_main", function (event, profileExtInfo1) {
$scope.changeprofilepicmodel1 = angular.copy(profileExtInfo1);
refreshServerFileList();
});
$scope.$on("pic_profiletwo_main", function (event, profileExtInfo2) {
$scope.changeprofilepicmodel2 = angular.copy(profileExtInfo2);
refreshServerFileList2();
});
$scope.onFileSelect = function ($files, callernumber, foldername, blobtype) {
if (callernumber == 1) {
$scope.blobModel = angular.copy($scope.changeprofilepicmodel1);
$scope.blobModel.folderName = foldername;
$scope.blobModel.blobTypeCode = blobtype;
} else if (callernumber == 2) {
$scope.blobModel = angular.copy($scope.changeprofilepicmodel2);
$scope.blobModel.folderName = foldername;
$scope.blobModel.blobTypeCode = blobtype;
}
$scope.selectedFiles = [];
$scope.model.progress = 0;
// Assuming there's more than one file being uploaded (we only have one)
// cancel all the uploads
if ($scope.upload && $scope.upload.length > 0) {
for (var i = 0; i < $scope.upload.length; i++) {
if ($scope.upload[i] != null) {
$scope.upload[i].abort();
}
}
}
$scope.upload = [];
$scope.uploadResult = [];
$scope.selectedFiles = $files;
// Ok, we only want one file to be uploaded
// let's take the first one and that's all
var $file = $files[0];
// Only first element, single file upload
(function (index) {
$scope.upload[index] = $upload.upload({
url: settings.constants.uploadURL,
headers: { 'myHeaderKey': 'myHeaderVal' },
method: 'POST',
data: $scope.blobModel,
file: $file,
fileFormDataName: 'myFile'
}).then(function (response) {
var look = response;
$scope.model.progress = 100;
// you could here set the model progress to 100 (when we reach this point we now that the file has been stored in azure storage)
$scope.uploadResult.push(response.data);
$scope.$emit('ClearUploadPics');
refreshServerFileList();
}, null, function (evt) {
// Another option is to stop here upadting the progress when it reaches 90%
// and update to 100% once the file has been already stored in azure storage
$scope.model.progress = parseInt(100.0 * evt.loaded / evt.total);
$scope.model.roundProgressData.label = $scope.model.progress + "%";
$scope.model.roundProgressData.percentage = ($scope.model.progress / 100);
});
})(0);
};
function refreshServerFileList() {
storageService.getFileList().then(function (data) {
$scope.model.fileList = data;
}
);
}
function initialize() {
refreshServerFileList();
}
initialize();
$scope.$on("ClearProgressBar", function (event) {
$scope.selectedFiles = null;
});
}]);
I hope this is okay and more readable.

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