Why is my Factory not getting instantiated/injected? - angularjs

Why is readingController not able to use the Romanize service? It always says Romanize is undefined inside the function. How can I get the service in scope?
var readingController = function (scope, Romanize){
scope.currentMaterial = scope.sections[scope.sectionNumber].tutorials[scope.tutorialNumber].material;
Romanize;
}
var app = angular.module('Tutorials', ['functions', 'tutorials']).controller('getAnswers', function ($scope, $element) {
$scope.sectionNumber = 0;
$scope.tutorialNumber = 0;
$scope.questionNumber = 0;
$scope.sections = sections;
$scope.loadFromMenu = function (sec, tut, first) {
if (tut === $scope.tutorialNumber && sec === $scope.sectionNumber && !first) {//if clicked on already playing tut
return;
}
if (tut !== undefined && sec !== undefined) {
$scope.tutorialNumber = tut;
$scope.sectionNumber = sec;
}
for (var x in sections) {
sections[x].active = "inactive";
for (var y in sections[x].tutorials){
sections[x].tutorials[y].active = "inactive";
}
}
var section = sections[$scope.sectionNumber];
section.active = "active";
section.tutorials[$scope.tutorialNumber].active = "active";
$scope.questionNumber = 0;
$scope.currentTutorialName = sections[$scope.sectionNumber].tutorials[$scope.tutorialNumber].name;
$scope.$apply();
if ($scope.sectionNumber === 0){
readingController($scope, app.Romanize);
}else if ($scope.sectionNumber === 1){
conjugationController($scope);
}
};
$scope.loadFromMenu(0,0, true);
var conjugationController = function (){
var loadNewVerbs = function (scope) {
scope.currentVerbSet = scope.sections[scope.sectionNumber].tutorials[scope.tutorialNumber].verbs;
if (scope.currentVerbSet === undefined) {
alert("Out of new questions");
return
}
scope.verbs = conjugate(scope.currentVerbSet[scope.questionNumber]);
scope.correct = scope.verbs.conjugations[0].text;
fisherYates(scope.verbs.conjugations);
scope.$apply();
};
loadNewVerbs($scope);
$scope.checkAnswer = function (answer) {
if($scope.sectionNumber === 0 && $scope.tutorialNumber === 0 && $("video")[0].currentTime < 160){
$scope.message = "Not yet!";
$(".message").show(300).delay(900).hide(300);
return;
}
answer.colorReveal = "reveal-color";
if (answer.text === $scope.correct) { //if correct skip to congratulations
$scope.questionNumber++;
setTimeout(function () {
loadNewVerbs($scope);
$scope.$apply();
}, 2000);
} else { //if incorrect skip to try again msg
if ($scope.sectionNumber === 0 && $scope.tutorialNumber === 0) {
start(160.5);
pause(163.8)
}
}
};
};
});
app.factory('Romanize', ['$http', function($http){
return{
get: function(){
$http.get(scope.sections[scope.sectionNumber].romanizeService).success(function(data) {
$scope.romanized = data;
});
}
};
}])

Update: based on comments/discussion below:
For a service to be instantiated, it has to be injected somewhere – not just anywhere – somewhere where Angular accepts injectables. Just inject it into your getAnswers controller – .controller('getAnswers', function ($scope, $element, Romanize) – then pass it to your "controller" function: readingController($scope, Romanize).
Since I don't think readingController is a real Angular controller, you can name the arguments whatever you want, so scope should be fine.
Original attempt at an answer:
Inject $scope not scope into your controller:
var readingController = function ($scope, Romanize){
Then I don't get any errors: Plunker.

Related

How to check whether an object is empty in a span?

I have some objects in my angularjs controller.
var app = angular.module("myApp", []);
app.controller("noteCtrl", function ($scope) {
$scope.draft = {};
$scope.notes = [];
$scope.note = {};
$scope.submit = function() {
$scope.notes.push($scope.note);
$scope.note = {};
};
$scope.save = function() {
if ($scope.button == "Save") {
$scope.draft = angular.copy($scope.note);
} else {
$scope.note = $scope.draft;
}
};
$scope.cancel = function() {
$scope.note = {};
}
});
I need to check whether the draft object is empty, and output the save successfully information.
<span data-ng-hide="draft == {}" style="color:green">Your note has been saved.</span>
I have also tried:
<span data-ng-hide="draft.length == -1" style="color:green">Your note has been saved.</span>
or
<span data-ng-hide="draft == ''" style="color:green">Your note has been saved.</span>
But all of them are failed.
Add function isEmptyObject in your controller:
var app = angular.module("myApp", []);
app.controller("noteCtrl", function ($scope) {
$scope.draft = {};
$scope.note = {};
$scope.notes = [];
$scope.save = function() {
if ($scope.button == "Save") {
$scope.draft = angular.copy($scope.note);
} else {
$scope.note = $scope.draft;
}
};
$scope.cancel = function() {
$scope.note = {};
}
$scope.isEmptyObject = function (obj) {
for (var i in obj) if (obj.hasOwnProperty(i)) return false;
return true;
};
});
Or you can use this function:
$scope.isEmptyObject = function (obj) {
return Object.keys(obj).length === 0;
}
HTML:
<span data-ng-hide="isEmptyObject(draft)" style="color:green">Your note has been saved.</span>
Please initialize null instead of empty object
$scope.draft = null;
And html should be
<span data-ng-hide="!draft" style="color:green">Your note has been saved.</span>
You can chek the condition inline in your span.
HTML:
<span data-ng-hide="Object.keys(draft).length === 0" style="color:green">Your note has been saved.</span>

How to get selected value from ng-autocomplete directive to controller

I am using a directive for auto complete / auto suggest in angular Js taken from http://demo.jankuri.com/ngAutocomplete/. It is working fine getting the data from server and filtering it. But I am facing problem into select and use that select item from the auto complete.
Here is the code of directive what I am using for this...
app.factory('ngAutocompleteService', ['$http', function($http)
{
var self = this;
self.getData = function (url, keyword) {
return $http.get(url, { query: keyword });
};
return self;
}])
app.directive('ngAutocomplete', ['$timeout','$filter','ngAutocompleteService',
function($timeout, $filter, ngAutocompleteService)
{
'use strict';
var keys = {
left : 37,
up : 38,
right : 39,
down : 40,
enter : 13,
esc : 27
};
var setScopeValues = function (scope, attrs) {
scope.url = base_url+attrs.url || null;
scope.searchProperty = attrs.searchProperty || 'skills';
scope.maxResults = attrs.maxResults || 10;
scope.delay = parseInt(attrs.delay, 10) || 300;
scope.minLenth = parseInt(attrs.minLenth, 10) || 2;
scope.allowOnlyResults = scope.$eval(attrs.allowOnlyResults) || false;
scope.placeholder = attrs.placeholder || 'Search...';
};
var delay = (function() {
var timer = 0;
return function (callback, ms) {
$timeout.cancel(timer);
timer = $timeout(callback, ms);
};
})();
return {
restrict: 'E',
require: '?ngModel',
scope: true,
link: function(scope, element, attrs, ngModel) {
setScopeValues(scope, attrs);
scope.results = [];
scope.currentIndex = null;
scope.getResults = function () {
if (parseInt(scope.keyword.length, 10) === 0) scope.results = [];
if (scope.keyword.length < scope.minLenth) return;
delay(function() {
ngAutocompleteService.getData(scope.url, scope.keyword).then(function(resp) {
scope.results = [];
var filtered = $filter('filter')(resp.data, {skills: scope.keyword});
for (var i = 0; i < scope.maxResults; i++) {
scope.results.push(filtered[i]);
}
scope.currentIndex = 0;
if (scope.results.length) {
scope.showResults = true;
}
});
}, scope.delay);
};
scope.selectResult = function (r) {
scope.keyword = r.skills;
ngModel.$setViewValue(r.skills);
scope.ngModel = r.skills;
ngModel.$render();
scope.showResults = false;
};
scope.clearResults = function () {
scope.results = [];
scope.currentIndex = null;
};
scope.hoverResult = function (i) {
scope.currentIndex = i;
}
scope.blurHandler = function () {
$timeout(function() {
if (scope.allowOnlyResults) {
var find = $filter('filter')(scope.results, {skills: scope.keyword}, true);
if (!find.length) {
scope.keyword = '';
ngModel.$setViewValue('');
}
}
scope.showResults = false;
}, 100);
};
scope.keyupHandler = function (e) {
var key = e.which || e.keyCode;
if (key === keys.enter) {
scope.selectResult(scope.results[scope.currentIndex]);
}
if (key === keys.left || key === keys.up) {
if (scope.currentIndex > 0) {
scope.currentIndex -= 1;
}
}
if (key === keys.right || key === keys.down) {
if (scope.currentIndex < scope.maxResults - 1) {
scope.currentIndex += 1;
}
}
if (key === keys.esc) {
scope.keyword = '';
ngModel.$setViewValue('');
scope.clearResults();
}
};
},
template:
'<input type="text" class="form-control" ng-model="keyword" placeholder="{{placeholder}}" ng-change="getResults()" ng-keyup="keyupHandler($event)" ng-blur="blurHandler()" ng-focus="currentIndex = 0" autocorrect="off" autocomplete="off">' +
'<input type="hidden" ng-model="skillIdToBeRated">'+
'<div ng-show="showResults">' +
' <div ng-repeat="r in results | filter : {skills: keyword}" ng-click="selectResult(r)" ng-mouseover="hoverResult($index)" ng-class="{\'hover\': $index === currentIndex}">' +
' <span class="form-control">{{ r.skills }}</span>' +
' </div>' +
'</div>'
};
}]);
I am unable to get value which is selected by ng-click="selectResult(r)" function. The value is showing into text field but not getting it into controller.
I was also using the same directive for showing the auto complete text box. I have tried the following for getting the selected value from auto complete.
in HTML
<div ng-controller="Cntrl as cntrl">
<ng-autocomplete ng-model="cntrl.selectedValue" url="url" search-property="keyword" max-results="10" delay="300" min-length="2" allow-only-results="true"></ng-autocomplete>
</div>
in JavaScript
app.controller('Cntrl', function($scope, $http) {
var self = this;
self.selectedValue = '';
$scope.getSelectedValue = function(){
console.log(self.selectedValue);
}
});
I hope this may help you.
I ran into the same issue. I ended up just watching the property from the details attribute in the ng-autocomplete input and it works pretty well.
$scope.$watch(function() {
return vm.location_result;
}, function(location) {
if (location) {
vm.location_list.push(location);
vm.location = '';
}
});
Fiddle Example: http://jsfiddle.net/n3ztwucL/
GitHub Gist: https://gist.github.com/robrothedev/46e1b2a2470b1f8687ad

AngularJS detect Bootstrap Environment

I am trying to use AngularJS to detect bootstrap environment. This is my code:
angular.module("envService",[])
.factory("envService", envService);
function envService($window){
return env();
////////////
function env(){
var w = angular.element($window);
var winWidth = w.width();
if(winWidth<768){
return 'xs';
}else if(winWidth>=1200){
return 'lg';
}else if(winWidth>=992){
return 'md';
}else if(winWidth>=768){
return 'sm';
}
}
}
The function works and return the value based on the window size. However, it will always return the same environment even if the window size is changed. How can I fix it?
You need to watch for the window resize event.
angular.module('envService',[])
.factory('envFactory', ['$window', '$timeout', function($window, $timeout) {
var envFactory = {};
var t;
envFactory.getEnv = function () {
var w = angular.element($window);
var winWidth = w.width();
if(winWidth<768){
return 'xs';
}else if(winWidth>=1200){
return 'lg';
}else if(winWidth>=992){
return 'md';
}else if(winWidth>=768){
return 'sm';
}
};
angular.element($window).bind('resize', function () {
$timeout.cancel(t);
t = $timeout(function () {
return envFactory.getEnv();
}, 300); // check if resize event is still happening
});
return envFactory;
}]);
angular.module('app',['envService']).controller('AppController', ['$scope', 'envFactory',
function($scope, envFactory) {
// watch for changes
$scope.$watch(function () { return envFactory.getEnv() }, function (newVal, oldVal) {
if (typeof newVal !== 'undefined') {
$scope.env = newVal;
console.log($scope.env);
}
});
}
]);

Need another set of eyes to debug angular unit tests

I am getting a series of error messages on my unit tests and Its been a few hours since I have made any progress. If anyone has the time to take a look it would be much appreciated. This is part of a larger controller so if anyone wants to see more code please let me know but I think this should cover it.
The errors I am getting are:
1)
Test 'CampaginLinksController getCampaignLinks():is loading' failed
Expected undefined to be true.
2)
Test 'CampaginLinksController getCampaignLinks():has a webSiteId that is not 0 and a buyRequestId that is not "" ' failed
Expected spy mockCampaginLinkSrv.getWebSiteBuyRequestLinks to have been called with [ 54, 8, 432, 200, { nextRowKey : 'fdsf2', nextPartitionKey : '5432gee' } ] but it was never called.
CampaginLinksCtrlSpec.js
describe('CampaignLinksController', function () {
//make module avalible to tests
beforeEach(module('pb.campaignLinks.controllers'));
beforeEach(module('ui.router'));
beforeEach(module('ui.bootstrap'));
var $controller;
var mockPromiseObj;
var length = 200;
var continuationToken = {
nextRowKey: 'fdsf2',
nextPartitionKey: '5432gee'
};
var mockCampaignLinkService = {
//all but delete must return a promiseObj
getCampaignLinks: jasmine.createSpy('mockCampaignLinkService.getCampaignLinks').and.returnValue(mockPromiseObj),
getCampaignBuyRequestLinks: jasmine.createSpy('mockCampaignLinkService.getCampaignBuyRequestLinks').and.returnValue(mockPromiseObj),
getWebSiteBuyRequestLinks: jasmine.createSpy('mockCampaignLinkService.getWebSiteBuyRequestLinks').and.returnValue(mockPromiseObj),
deleteCampaignLink: jasmine.createSpy('mockCampaignLinkService.deleteCampaignLinks').and.returnValue(mockPromiseObj)
};
var mockGlobal = {
activeOrganizationId: 54
};
var mockCampaignLinks = true;
var mockCurrentView;
beforeEach(inject(function (_$controller_) {
$controller = _$controller_;
}));
beforeEach(inject(function ($rootScope, $q) {
scope = $rootScope.$new();
var mockPromiseObj = {
hello: "world",
then: function (orgId, entityId) {
var defer = $q.defer();
defer.resolve(this.account);
return defer.promise;
}
}
controller = $controller('CampaignLinksController',
{
$scope: scope,
//$stateParams: mockStateParams,
global: mockGlobal,
campaignLinks: mockCampaignLinks,
campaignLinkService: mockCampaignLinkService,
currentVeiw: mockCurrentView,
promiseObj: mockPromiseObj
});
}));
describe('getCampaignLinks()', function () {
beforeEach(function () {
mockCurrentView = {
campaignId: 32,
webSiteId: 8
};
});
//describing loading
it('is loading', function () {
scope.getCampaignLinks(mockCurrentView, length, continuationToken);
expect(mockCampaignLinks.loading).toBe(true);
});
it('is not loading', function () {
mockCampaignLinks = false;
scope.getCampaignLinks(mockCurrentView, length, continuationToken);
expect(mockCampaignLinks.loading).toEqual(undefined);
});
it('has a webSiteId that is not 0 and a buyRequestId that is not "" ', function () {
mockCurrentView.buyRequestId = 432;
scope.getCampaignLinks(mockCurrentView, length, continuationToken);
expect(mockCampaignLinkService.getWebSiteBuyRequestLinks).toHaveBeenCalledWith(mockGlobal.activeOrganizationId, mockCurrentView.webSiteId, mockCurrentView.buyRequestId, length, continuationToken);
// must check that what is returned is a promise
expect(scope.promiseObj).toEqual(mockPromiseObj);
});
});
CampaginLinksController.js
$scope.getCampaignLinks = function (currentView, length, continuationToken) {
// When loading list items, display loading image
if ($scope.campaignLinks) $scope.campaignLinks.loading = true;
var promiseObj = null;
if (currentView.campaignId && currentView.campaignId !== 0 && !currentView.buyRequestId) {
promiseObj = campaignLinkService.getCampaignLinks(global.activeOrganizationId, currentView.campaignId, length, continuationToken)
} else if (currentView.campaignId && currentView.buyRequestId && currentView.campaignId !== 0 && currentView.buyRequestId !== '') {
promiseObj = campaignLinkService.getCampaignBuyRequestLinks(global.activeOrganizationId, currentView.campaignId, currentView.buyRequestId, length, continuationToken);
} else if (currentView.webSiteId && currentView.buyRequestId && currentView.webSiteId !== 0 && currentView.buyRequestId !== '') {
promiseObj = campaignLinkService.getWebSiteBuyRequestLinks(global.activeOrganizationId, currentView.webSiteId, currentView.buyRequestId, length, continuationToken);
}
if (promiseObj) {
promiseObj.then(function (data) {
// If there are already some campaign links being displayed, add newly loaded list to the end
if ($scope.campaignLinks) {
$scope.campaignLinks.continuationToken = data.continuationToken;
$scope.campaignLinks.total += data.total;
$.each(data.items, function (index) {
$scope.campaignLinks.items.push(data.items[index]);
});
} else {
// Otherwise add loaded list to scope
$scope.campaignLinks = data;
}
// When done loading, hide loading image
$scope.campaignLinks.loading = false;
});
}
};
First test: When you initialize mockCampaignLinks, you should give it an object, not true. Also, you probably should initialize it in beforeEach since you mutate it in the tests.
Second test: getCampaignBuyRequestLinks is the method being called.

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