Uploading a `XML` file not working as per expected - angularjs

I required to upload a xml file in to server using the angular resource. i am trying but getting an error as Uncaught TypeError: server.uploadXML.post is not a function
any one correct me or show me the correct way to handle this?
to do this process, I am using controller and directive with my html.
I am very new, please guide me wherever I made mistaken.
here is my controller function : //i am calling from directive
$scope.uploadFile = function ( newFile, id ) {
var fileData = new FormData();
fileData.append('file', newFile[0], newFile[0].name);
// console.log("new file", "$scope.packageId", $scope.packageId, "$scope.contractorId", $scope.contractorId, newFile, info );
server.uploadXML.post({
packageId: $scope.packageId,
contractorId : $scope.contractorId,
contractId : id
}, { save: {
type: 'POST',
data: fileData,
cache: false,
dataType: 'json',
processData: false,
contentType: "application/octet-stream",
success : function ( data ) {
},
error : function ( error ) {
cosole.log( error );
}
}} );
}
Here is my directive:
//file upload handled here
var uploadFileDirective = function () {
return {
restrict : 'C',
scope : {
info:"=",
upload:"="
},
link:function ( scope, element, attrs ) {
element.on('change', function ( event ) {
var files = event.target.files;
scope.upload(files, scope.info ); //calling controller
})
}
}
}
angular.module("tcpApp")
.directive("uploadFileDirective", uploadFileDirective);
Here is my HTML :
<div class="row row3">
<div class="cell">
<a ng-href="">Contract Details</a>
<span class="fileUpload">
Upload Report
<!-- hanlded by directive by class name -->
<input info="contractor.Id" upload="uploadFile" class="uploadField upload-file-directive" type="file" />
</span>
</div>
</div>
</div>
I am using my server.js file to upload my file, here is the server.js file:
(function () {
"use strict";
angular
.module("tcpApp")
.factory("server", ['$resource', function ($resource) {
var base = 'http://azvsptcsdev02:678/_vti_bin/CPMD.WEBSERVICE/ProjectInfoService.svc/';
return {
subPage : $resource( base + 'GetSubProjects/:id'),
splash : $resource( base + 'GetProjectDetails'),
projectSummary : $resource( base + 'GetProjectByID/:id', {id : '#id'}), //at the top on the summary page
contractorsList : $resource( base + 'Contracts/:projectId/:subProjectId/:phaseId/:disciplineId'), //left side list of contractos
contractorInfo : $resource( base + 'Projects/:projectId/:subProjectId/:contractId/:disciplineId/:staticId'), //summary page getting contractor info
allProjectList : $resource( base + 'GetAllProjects'), //getting all project for all project page
allSubProjects : $resource( base + 'GetAllSubProjects/:packageId'),
allContracts : $resource( base + 'AllContracts/:packageId/:contractorId'),
uploadXML : $resource( base + 'UploadContract/:packageId/:contractorId/:contractId')
}
}]);
})();

In your server.js file, when you do
uploadXML : $resource( base + 'UploadContract/:packageId/:contractorId/:contractId')
$resource returns on abject with the following methods available:
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
See the angular documentation.
So server.uploadXML.post is indeed not defined (that's why you get the error). Try using server.uploadXML.save instead which corresponds to the http POST method.

Related

Kendo UI panelBar content doesnt compile Angular

i i have a kendo UI panelBar, and i want to load data dynamically. I want inside panelBar option to have a template that use Angular. I have this part of code but this doesnt work.
$http({
method: 'GET',
url: '/PDFEditor/GetPDFDocumentInfo',
params: { fileId: fileId }
}).then(function successCallback(response) {
$scope.test = "My name is: <h1>Bond, James Bond </h1>";
var tml = '<div id="testId"></div>';
$scope.pdfInfo = response.data;
$scope.appendToPanelBar([{
text: 'Info',
content: tml
}]);
document.getElementById("testId").innerHTML = "<p ng-bind-html=\"test\"></p> {{test}}";
}, function errorCallback(response) {
//todo
console.error('todo error handling');
});
I also tried without to get element by id and add directly to content: '{{test}}'. Seems that AngularJS doesn't compile this template.
I find the solution!!
$scope.test = "My name is: <h1>Bond, James Bond </h1>";
var tml = '<div id="testId"></div>';
var data = $compile('<p>{{test}}</p>')($scope);
console.log(data)
$scope.pdfInfo = response.data;
$scope.appendToPanelBar([{
text: 'Info',
content: tml
}]);
document.getElementById("testId").append(data[0]);
cheers!

Updating the model with file URL to be saved on submit

I have been able to successfully upload an image with a custom field template calling a function that handles the upload. It then gathers the return url and from there, i have no idea how to insert it back into the field for saving with the form.
Any help would be much appreciated :)
Here is my code:
var myApp = angular.module('myApp', ['ng-admin', 'backand', 'ngFileUpload']);
//myApp.directive('dashboardSummary', require('./dashboards/dashboardSummary'));
myApp.config(['BackandProvider', function(BackandProvider) {
BackandProvider.setAppName('');
BackandProvider.setSignUpToken('');
BackandProvider.setAnonymousToken('');
}]);
myApp.config(function(RestangularProvider) {
// add a response interceptor
RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
var extractedData;
// .. to look for getList operations
if (operation === "getList") {
// .. and handle the data and meta data
extractedData = data.data;
extractedData.meta = data.data.__metadata;
} else {
extractedData = data;
}
return extractedData;
});
});
myApp.config(['NgAdminConfigurationProvider','BackandProvider', function (nga, BackandProvider, $scope) {
// create an admin application
BackandProvider.setAppName('');
BackandProvider.setSignUpToken('');
BackandProvider.setAnonymousToken('');
var admin = nga.application('Pocket Release Admin Manager')
.baseApiUrl('https://api.backand.com/1/objects/'); // main API endpoint#
// Users
var user = nga.entity('users');
user.listView().fields([
nga.field('firstName').isDetailLink(true),
nga.field('lastName'),
nga.field('email')
]);
user.creationView().fields([
nga.field('firstName'),
nga.field('lastName'),
nga.field('email', 'email')
]);
user.editionView().fields(user.creationView().fields());
// add the user entity to the admin application
admin.addEntity(user);
// Platforms
var platforms = nga.entity('platforms');
platforms.listView().fields([
nga.field('id'),
nga.field('platform_name'),
]);
platforms.creationView().fields([
nga.field('id'),
nga.field('platform_name'),
nga.field('platform_id')
]);
platforms.editionView().fields(platforms.creationView().fields());
admin.addEntity(platforms);
var data = {};
// Games
var games = nga.entity('games');
games.listView().fields([
nga.field('id'),
nga.field('game_title').isDetailLink(true),
nga.field('game_url'),
nga.field('platforms', 'reference')
.targetEntity(platforms)
.targetField(nga.field('platform_name'))
.label('Platform')
]);
games.creationView().fields([
nga.field('game_title'),
nga.field('image').template('<img ng-src="{{game_url}}" ng-show="game_url">'),
nga.field('game_url', 'file').uploadInformation({'url':'', 'apifilename':'game_url'}).template('<div ng-controller="main"><label class="btn btn-default btn-file">Browse<input id="fileInput" field="::field" value="entry.values[{{main}}]" entry="entry" entity="::entity" form="formController.form" datastore="::formController.dataStore" type="file" style="display: none;" accept="*/*" ng-click="initUpload()" /></label></div>', true),
nga.field('platforms'),
nga.field('game_description'),
nga.field('game_boxart'),
nga.field('game_release_uk', 'date'),
nga.field('game_release_us', 'date'),
nga.field('game_release_eu', 'date')
]);
games.editionView().fields(games.creationView().fields());
admin.addEntity(games);
// Dash
admin.dashboard(nga.dashboard()
.addCollection(nga.collection(games)
.name('total_games')
.title('Total Games')
.fields([
nga.field('game_title')
])
.sortField('game_title')
.sortDir('DESC')
.order(1)
).template(`
<div class="row dashboard-starter"></div>
<dashboard-summary></dashboard-summary>
<div class="row dashboard-content">
<div class="col-lg-6">
<div class="panel panel-default">
<ma-dashboard-panel collection="dashboardController.collections.total_games" entries="dashboardController.entries.total_games" datastore="dashboardController.datastore"></ma-dashboard-panel>
</div>
</div>
</div>
`));
// Menu Customize
// customize menu
admin.menu(nga.menu()
.addChild(nga.menu(user).icon('<span class="glyphicon glyphicon-file"></span> ')) // customize the entity menu icon
.addChild(nga.menu(games).icon('<span class="glyphicon glyphicon-folder-open"></span> ')) // you can even use utf-8 symbols!
.addChild(nga.menu(platforms).icon('<span class="glyphicon glyphicon-tags"></span> '))
);
// attach the admin application to the DOM and execute it
nga.configure(admin);
}]);
myApp.controller('main', function ($scope, $rootScope, $location, $http, Backand) {
// Image upload stuff
$scope.initUpload = function(){
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
imageChanged(fileInput);
});
}
function imageChanged(fileInput) {
//read file content
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload = function(e) {
upload(file.name, e.currentTarget.result).then(function(res) {
$scope.imageUrl = res.data.url;
$scope.filename = file.name;
return res.data.url;
}, function(err){
alert(err.data);
});
};
reader.readAsDataURL(file);
};
function upload(filename, filedata) {
// By calling the files action with POST method in will perform
// an upload of the file into Backand Storage
return $http({
method: 'POST',
url : Backand.getApiUrl()+'/1/objects/action/games',
params:{
"name": 'files'
},
headers: {
'Content-Type': 'application/json'
},
// you need to provide the file name and the file data
data: {
"filename": Math.floor(Date.now() / 1000) + ''+ filename.match(/\.[0-9a-z]+$/i),
"filedata": filedata.substr(filedata.indexOf(',') + 1, filedata.length) //need to remove the file prefix type
}
}).success(function(data, status, headers, config) {
//$scope.game_url = data.url;
//$("#game_url").addClass("ng-dirty ng-valid-parse ng-touched").removeClass("ng-pristine ng-untouched");
//$("#game_boxart").val(data.url).addClass("ng-dirty ng-valid-parse ng-touched").removeClass("ng-pristine ng-untouched");
return data.url;
});
};
});
Have you tried making a PUT call to backand in order to save this url in the relevant column?
return $http({
method: 'PUT',
url : Backand.getApiUrl()+'/1/objects/games/YOUR_GAME_ID',
headers: {
'Content-Type': 'application/json'
},
data: {
urlColumn:imageUrl
}
}).success(function(data, status, headers, config) {
.....
});

Data is stuck in $http .then method

Hi I am trying to display my data but when i tried to display it on my html using angular data wont pass through. checked the console and data was there. here is my html.
<ion-view view-title="">
<ion-content>
<!-- <div class="cards">
<div class="item item-image">
<img src="img/banner-children.jpg"></img>
</div>
</div> -->
<div class="list card padding" ng-repeat="charity in charityList">
<a href="#/app/charitypage/{{charity.charity_id}}" class="positive ">
<img class="char-logo img-thumb" ng-src="{{charity.logo}}">
<div class="char-info">
<h3 class="char-name text-pink">
<i class="ion-chevron-right text-pink btn-category"></i>
{{charity.charity_name}}</h3>
<p class="dark">{{charity.description}}</p>
</div>
</a>
</div>
</ion-content>
and here is my controller
angular.module('subCategory.controllers', [])
.controller('subCatCtrl', function($scope, $state, $http) {
$scope.getCategoryList = function(category){
$scope.charityList = {};
var categoryListData = {
charityCategory : category
}
$http({
method: 'POST',
header: {'Content-Type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost/filantrome/Main/getCategoryList',
data: categoryListData
}).then(
function success( response ) {
$scope.charityList= response.data;
console.log($scope.charityList);
$state.go('app.subcat');
},
function error( response ) {
$scope.charityList = response.data;
console.log($scope.charityList);
// handle error
}
);
console.log($scope.charityList);
};
});
i can see the data that i was requesting on the console.log() inside the success function. but when i get out of the .then(); function $scope.charityList is empty.
what am i missing here? thanks!
Seems problem is in state change. To fix this you can use service to store received JSON
angular.module('subCategory.controllers', []).service(charityService, charityService);
/* #ngInject */
function charityService($http) {
var charityList = [];
var service = {
getData: getData,
getCharityList: getCharityList
};
return service;
function getCharityList() {
return charityList ;
}
function getData(categoryListData) {
$http({
method: 'POST',
header: {'Content-Type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost/filantrome/Main/getCategoryList',
data: categoryListData
}).then(
function success( response ) {
charityList = response.data;
console.log(charityList );
$state.go('app.subcat'); // you can also change state here
},
function error( response ) {
$scope.charityList = response.data;
console.log($scope.charityList);
// handle error
}
);
}
}
then post data with controller function
$scope.getCategoryList = function(category){
var categoryListData = {
charityCategory : category
}
charityService.getData(categoryListData);
}
after state changes controller will get charityList from service
angular.module('subCategory.controllers', []) .controller('subCatCtrl',
function($scope, $state, $http, charityService) {
$scope.charityList = charityService.getCharityList();
// ...
As you have posted your console.log output, I can see that you have a single object receiving and assigning to charityList but you have an ng-repeat on the element. So, I think you should change $scope.charityList = {}; to $scope.charityList = []; or you can output this variable in the html to see whats going on like {{charityList}}.

Angular-ui-router dependency error

Ok so, for the record, i had a working project, i had to change the grunt workflow of it, and now angular-ui-router throws me an ununderstandable error.
here is what i get when i follow angularjs links :
Failed to instantiate module app due to:
Failed to instantiate module ui.router due to:
Failed to instantiate module ui.router.state due to:
Uncaught Error: [$injector:modulerr]
http://errors.angularjs.org/1.3.15/$injector/modulerr?p0=app&p1=Error%3A%20…Flocalhost%3A8080%2Fapp%2Fcomponents%2Fangular%2Fangular.min.js%3A38%3A135)(anonymous
function) # angular.min.js:6(anonymous function) # angular.min.js:35r
# angular.min.js:7g # angular.min.js:34ab # angular.min.js:38d #
angular.min.js:17uc # angular.min.js:18Jd #
angular.min.js:17(anonymous function) #
angular.min.js:250n.Callbacks.j #
jquery.min.js:2n.Callbacks.k.fireWith # jquery.min.js:2n.extend.ready
# jquery.min.js:2I # jquery.min.js:2
im quite lost, i tryed downgrading to angularjs 1.3.15, didnt bring anything. The order of inclusion of scripts is the following :
components/html5-boilerplate/dist/js/vendor/modernizr-2.8.3.min.js
components/jquery/dist/jquery.min.js
components/highcharts/highcharts.js
components/bootstrap/dist/js/bootstrap.min.js
components/socket.io-client/socket.io.js
components/bootstrap-switch/dist/js/bootstrap-switch.min.js
components/lodash/lodash.min.js
components/gsap/src/minified/TweenMax.min.js
components/gsap/src/minified/easing/EasePack.min.js
components/PreloadJS/lib/preloadjs-0.6.1.min.js
components/humanize-duration/humanize-duration.js
components/momentjs/min/moment-with-locales.min.js
components/angular/angular.min.js
components/angular-ui-router/release/angular-ui-router.min.js
components/angular-cookies/angular-cookies.min.js
components/ng-tags-input.min/ng-tags-input.min.js
components/angular-sanitize/angular-sanitize.min.js
components/angular-animate/angular-animate.js
components/restangular/dist/restangular.min.js
components/angular-fullscreen/src/angular-fullscreen.js
components/angular-bootstrap/ui-bootstrap.min.js
components/angular-bootstrap/ui-bootstrap-tpls.min.js
components/angular-bootstrap-switch/dist/angular-bootstrap-switch.min.js
components/highcharts-ng/dist/highcharts-ng.min.js
components/ng-droplet/dist/ng-droplet.min.js
components/angular-timer/dist/angular-timer.min.js
src/constants-app.js src/app.js
src/admin/admin-controller.js
src/admin/events/events-controller.js
src/admin/moderation/bans-controller.js
src/admin/moderation/message-modal/message-modal-controller.js
src/admin/moderation/moderation-controller.js
src/admin/partners/partners-controller.js
src/admin/reports/reports-controller.js
src/admin/user/invites/invites-controller.js
src/admin/user/linked/linked-accounts-controller.js
src/admin/user/password/password-controller.js
src/admin/user/user-controller.js src/admin/votes/votes-controller.js
src/adminboard/adminboard-controller.js src/root-controller.js
src/shared/alerts/alerts-controller.js
src/shared/alerts/alerts-directive.js
src/shared/clock/clock-directive.js src/shared/crap.js
src/shared/filters/url-filter.js src/shared/main-controller.js
src/shared/modals/confirm-modal-controller.js
src/shared/purchase-credit-modal/purchase-credit-controller.js
src/shared/purchase-modal/purchase-modal-controller.js
src/shared/services/event-service.js
src/shared/services/message-service.js
src/shared/services/modal-helper-service.js
src/shared/services/queue-service.js
src/shared/services/socket-service.js
src/shared/services/user-service.js
src/shared/services/vote-service.js
src/shared/spinner/spinner-directive.js
src/shared/spinner/spinner-service.js
src/wall/bottomOverlay/bottomOverlay-controller.js
src/wall/bottomOverlay/bottomOverlay-directive.js
src/wall/counters/counters-controller.js
src/wall/counters/counters-directive.js
src/wall/messages/messages-directive.js
src/wall/messages/messages-settings-controller.js
src/wall/slideshow/slideshow-directive.js
src/wall/slideshow/slideshow-settings-controller.js
src/wall/topOverlay/topOverlay-controller.js
src/wall/topOverlay/topOverlay-directive.js
src/wall/vote/vote-directive.js src/wall/wall-controller.js
I separated the scrips in interesting blocks. Where i include angular, ui router, and other pieces.
Here is my app.js file content :
// Declare modules.
angular.module('app')
//ui.routes
.config(['$stateProvider','$urlRouterProvider','$locationProvider',function($stateProvider, $urlRouterProvider, $locationProvider) {
"use strict";
$locationProvider.html5Mode(true); //Remove # in angular urls.
$stateProvider
.state('root',{ //here we resolve all the application wide stuff. Like user.
url : '',
controller : 'rootController',
template : '<ui-view id="rootView"></ui-view>',
resolve : {
user : ['Restangular',function(Restangular){
return Restangular.all('users').customGET('self');
}]
}
})
//MODALS
//BUY CREDIT
.state('purchaseCredit',{
url : '/purchaseCredit'
})
.state('slideShowSettings',{
url : '/slideShowSettings'
})
.state('messagesSettings',{
url : '/messageSettings'
})
.state('root.admin',{
url : '/admin',
templateUrl : 'src/admin/admin.html',
controller : 'adminController'
})
//show user account infos, and actions.
.state('root.admin.user',{
url : '/user',
templateUrl : 'src/admin/user/user.html',
controller: 'userController'
})
//edit user password
.state('root.admin.user.password',{
url : '/password',
templateUrl : 'src/admin/user/password/password.html',
controller : 'passwordController'
})
//show invites list.
.state('root.admin.user.invites',{
url : '/invites',
templateUrl : 'src/admin/user/invites/invites.html',
controller : 'invitesController',
resolve : {
invites: ['Restangular', 'user', function (Restangular, user) {
return Restangular.all('invites').getList({parentId : user._id}); //todo limit to my invites.
}]
}
})
//show one invite.
/* .state('root.admin.user.invites.detail',{
url : '/:id',
templateUrl : 'src/admin/user/invites/invite.html',
controller : 'inviteController',
resolve : {
invite : ['$stateParams', function($stateParams){
if(!$stateParams.id){ return {}; }
return Restangular.one('invites',$stateParams.id).get();
}]
}
})*/
/* LINKED ACCOUNTS */
//list of linked accounts ( people who accepted invite )
.state('root.admin.user.linkedAccounts',{
url : '/linkedAccounts',
templateUrl : 'src/admin/user/linked/linkedAccounts.html',
controller : 'linkedAccountsController',
resolve : {
linkedAccounts : ['Restangular', 'user', function (Restangular, user) {
var query = { parent : user._id/*, sort : '_id', limit : 20, skip : 0*/};
console.warn('gonna fetch', query);
return Restangular.all('users').getList(query);
}]
}
})
.state('root.admin.events',{
url : '/events',
templateUrl : 'src/admin/events/events.html',
controller : 'eventsController'
})
.state('root.admin.moderation', {
url: '/moderation',
templateUrl : 'src/admin/moderation/moderation.html',
controller: 'moderationController'
})
.state('root.admin.bans',{
url : '/bans',
templateUrl : 'src/admin/moderation/bans.html',
controller : 'bansController'
})
.state('root.admin.reports',{
url : 'admin.reports',
templateUrl : 'src/admin/reports/reports.html',
controller : 'reportsController'
})
.state('root.admin.votes',{
url : '/votes/:id',
templateUrl : 'src/admin/votes/votes.html',
controller : 'votesController'
})
.state('root.wall',{
url : '/wall/:eventId',
templateUrl : 'src/wall/wall.html',
controller: 'wallController'
})
.state('root.vote',{ //display vote for conference. integration in powerpoint.
url : '/vote/:voteId',
templateUrl : 'src/vote/vote.html',
controller : 'voteController'
})
.state('root.adminboard',{
url : '/adminboard',
templateUrl : 'src/adminboard/adminboard.html',
controller : 'adminBoardController'
});
$urlRouterProvider.otherwise('/admin/events'); //redirect. default to events page.
}])//restangular
.config(['RestangularProvider',function(RestangularProvider) {
"use strict";
RestangularProvider
.setBaseUrl('/api/v1/')
.setRestangularFields({
id: "_id"
})
.setDefaultHeaders({'Content-Type': 'application/json'})
.setRequestInterceptor(function(elem, operation, what) {
if (operation === 'put' || operation === 'post') {
elem._id = undefined;
elem.__v = undefined;
return elem;
}
return elem;
});
}]).run(['Restangular', '$window','socketService', function(Restangular, $window, socketService ){
'use strict';
Restangular.extendModel('events', function(model) {
if(typeof model !== 'object'){ //todo sometimes ( reset ) gives back a non object.
return false;
}
model.isStarted = function() { //adds started method to all events objects.
return (this.startedUntil ? ( (new Date(this.startedUntil).getTime() > Date.now())) : false);
};
model.hasMessages = function(){
return model.config.phone ||((model.counts.sms + model.counts.appli + model.counts.admin) > 0);
};
model.hasPhone = function(){
return (typeof model.config.phone === 'string');
};
model.hasFacebook = function(){
return model.config.facebookAccounts;
};
model.hasTweeter = function(){
return model.config.twitterHashtags.length;
};
model.hasInstagram = function(){
return model.config.instagramHashtags.length;
};
return model;
});
Restangular.extendModel('users', function(model){ //if user has trial offer and event is started.
model.isTrial = function(){
_.filter(model.offers,function(offer){ //todo make this a function of user? (isTrial)
return (offer.type === 'trial' && (new Date(offer.until).getTime() > Date.now()) );
});
};
return model;
});
Restangular.setErrorInterceptor(
function(response, deferred, responseHandler) {
if (response.status === 401) {
console.log("Login required... ");
$window.location.href = '/login';
} else if (response.status === 404) {
console.log("Resource not available...");
} else if (response.status === 500) {
console.log("Response received with HTTP error code: " + response.status );
return true;
} else if (response.status === 403){
return true;
}
return false; // stop the promise chain
}
);/*.setDefaultRequestParams({ socketId : socketService.socket.id});*/
}]).run(['$rootScope','$modal',function($rootScope, $modal){
"use strict";
/**
* Listen to the `$stateChangeStart` event
*/
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
//if the new state is not "terms", then ignore it
switch(toState.name){
case 'purchaseCredit' :
// console.warn('opencredit!');
$modal.open({
templateUrl : 'src/shared/purchase-credit-modal/purchase-credit-modal.html',
controller : 'purchaseModalController',
resolve : {
user : function(){return toParams.user; }
}
});
break;
case 'slideShowSettings' :
//console.error('look here toparams',toParams);
$modal.open({
templateUrl : 'src/wall/slideshow/slideshow-settings-modal.html',
controller : 'slideshowSettingsController',
size:'sm'
});
break;
case 'messagesSettings' :
$modal.open({
templateUrl : 'src/wall/messages/messages-settings-modal.html',
controller : 'messagesSettingsController',
size:'sm'
});
break;
default : //its not a modal state.
return;
}
event.preventDefault(); //prevent transition to the modal's state.
});
}]).controller('HelloWorldController', ['$scope', function($scope) {
"use strict";
$scope.greeting = 'Hello World!';
}]);
And here is my constant-app.js content :
angular.module('app', ['ngSanitize', 'ngCookies', 'ngAnimate', 'ui.router', 'highcharts-ng', 'restangular', 'FBAngular', 'ngDroplet', 'ngTagsInput', 'ui.bootstrap', 'ngDroplet', 'frapontillo.bootstrap-switch', 'timer'])
.constant('App.constants.version', '0.2.0');
what could cause this error? im stuck since several days. I tryed commenting out things but error comes back.

How to start upload file in Angular JS?

I use Angular JS library angular-file-upload.
I moved init FileUploader code from controller to factory method:
.factory('UploadFilesHash', ['FileUploader', function (FileUploader) {
var uploader;
return {
uploadInit: function (data){
uploader = new FileUploader({
url: '/upload/',
formData: data,
alias: 'files',
autoUpload: true
});
// FILTERS
uploader.filters.push({
name: 'imageFilter',
fn: function (item /*{File|FileLikeObject}*/, options) {
var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
}
});
// CALLBACKS
uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {
//console.info('onWhenAddingFileFailed', item, filter, options);
};
});
}
So, in controller I do inject this factory and call init function:
Controller:
$scope.startFromView = function (){
UploadFilesHash.uploadInit(data);
}
HTML:
<span ng-click="startFromView()">
<input type="file" nv-file-select="" uploader="uploader" multiple />
</span>
So, problem is that I call function startFromView() then there is no file upload. Earlier this code was at controller and all work.

Resources