Angularjs multiple file upload in single request - angularjs

<input type="file" ng-model="item.files" ng-change="item.onSelectFile()"/>
function MyController($scope, httpSrvc){
function Item(){
this.name = "";
this.files = [];
this.onSelectFile = function(file){
if(this.files.length < 3){
this.files.push(file);
}
}
this.onSubmit = function(){
let formData = new FormData();
formData.append("name",this.name);
for(let i = 0 ; i < this.files.length ; i++){
formData.append(`page_${i+1}`,this.files[i]);
}
httpSrvc.post(url,formData)
.then(function(res){console.log(res)})
.catch(function(err){console.log(err)})
}
}
function init(){
$scope.item = new Item();
}
}
is it possible to store file in a array? what value should I set to ng-model?

Check following code.
Points to note :
You need to attach onchange event and get the scope with angular.element(this).scope()
You need to wrap your code inside $scope.$apply. This is required if you want to display the list of files on the view. This is necessary since the files array is not tracked by angular since it is not assigned as ng-model.
'Content-Type': undefined is required in the http headers
angular.module('myApp', []).controller('MyController', ['$scope', '$http',
function MyController($scope, $http) {
function Item() {
this.name = "";
this.files = [];
this.onSelectFile = function(event) {
$scope.$apply(() => {
let file = event.target.files[0];
if (this.files.length < 3) {
this.files.push(file);
}
});
}
this.onSubmit = function() {
let formData = new FormData();
formData.append("name", this.name);
for (let i = 0; i < this.files.length; i++) {
formData.append(`page_${i+1}`, this.files[i]);
}
let url = "www.google.com";
let request = {
method: 'POST',
url: url,
data: formData,
headers: {
'Content-Type': undefined
}
};
$http(request)
.then(function(res) {
console.log(res)
})
.catch(function(err) {
console.log(err)
})
}
}
function init() {
$scope.item = new Item();
}
init();
document.querySelector('input[type="file"]').addEventListener('change', (event) => $scope.item.onSelectFile(event));
}
]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyController">
<input type="file" ng-model="item.file" />
<ul>
<li ng-repeat="file in item.files">
{{ file.name }}
</li>
</ul>
<input type="button" value="Submit" ng-click="item.onSubmit()">
</div>

Related

Showing dynamic content inside ngRepeat

Struggling to show dynamic content inside a ngRepeat. When it comes time to show my promise content, I'm getting an empty object {}:
<div ng-controller="DemoCtrl">
<div class="sidebar" ng-repeat="row in rows">
<div class="row">
<input type="checkbox">
<div class="name">{{row.name}}</div>
<div class="title">{{map[$index]}}</div>
</div>
</div>
</div>
and the controller:
function DemoCtrl($scope, $http, $q) {
const rows = function() {
const rows = [];
for (let i = 0; i < 12; i++) {
rows.push({
id: `demo-${i}`,
name: `Demo ${i}`
});
}
return rows;
};
$scope.rows = rows();
$scope.map = [];
// $scope.$watch($scope.map, function (oldValue, newValue) {
// console.log(oldValue, newValue);
// });
function _data() {
// const promises = [];
for (let i = 0; i < $scope.rows.length; i++) {
var defer = $q.defer();
$http.get(`https://jsonplaceholder.typicode.com/posts/${i + 1}`).then(function(post) {
defer.resolve(`${post.data.title.substring(0, 10)}...`);
});
$scope.map.push(defer.promise);
// promises.push(defer.promise);
}
// return $q.all(promises);
return $q.all($scope.map);
}
function _init() {
_data().then(function(data) {
$scope.map = data; // why aren't we getting here?
});
};
_init();
}
Plunker here: https://plnkr.co/edit/2BMfIU97Moisir7BBPNc
I've tinkered with some other ideas such as trying to add a $watch on the $scope object after the value changes, but I'm not convinced this will help in any way. Some lingering questions I have:
From what I understand, you can use a promise inside a template so how/why does this change inside a ngRepeat?
Why isn't my callback for $q.all getting called?
If this is not the right approach, what is?
In Angular you will almost never need to use $q.
You can simply fill an array of posts titles after each $http.get
function DemoCtrl($scope, $http) {
const rows = function () {
const rows = [];
for (let i = 0; i < 12; i++) {
rows.push({
id: `demo-${i}`,
name: `Demo ${i}`
});
}
return rows;
};
$scope.rows = rows();
$scope.map = [];
function _init() {
for (let i = 0; i < $scope.rows.length; i++) {
$http.get(`https://jsonplaceholder.typicode.com/posts/${i + 1}`).then(function (post) {
$scope.map.push(post.data.title);
});
}
}
_init();
}
https://plnkr.co/edit/zOF4KNtAIFqoCOfinaMO?p=preview

Scope from controller does not pass to directive

I have a html like this :
<div id="create-group" ng-controller="groupCreateController">
<div id="container">
<h1>Create group</h1>
<div class="row">
<div class="col-md-4"><input placeholder="Group Name.." ng-model="group.name"></div>
<div class="col-md-8">
<label>Group Description : </label>
<textarea ng-model="group.description"> </textarea>
</div>
</div>
<br/>
<div class="row">
<div class="col-sm-6">
<usermgr-permission-list group="group"></usermgr-permission-list>
<button type="button" class="btn btn-md btn-primary" ng-click="btnSave_click($event)">SAVE</button>
</div>
<div class="col-sm-6">
<usermgr-user-list group="group"></usermgr-user-list>
</div>
</div>
</div>
</div>
My controller is :
(function (module) {
'use strict';
module.controller('groupCreateController', function ($scope, $rootScope, $routeParams, $location, userGroupService, $mdDialog) {
$scope.group = [];
$scope.init = function () {
if ($routeParams.hasOwnProperty('id')) {
//edit mode
// $scope.trans.heading = 'Edit Release';
// $scope.trans.saveBtn = 'Save';
var id = parseInt($routeParams.id);
getUserGroup(id);
} else {
$scope.group[0].id = 0;
$scope.group[0].permissions = [];
$scope.assignedPermissions = [];
$scope.enrolledUsers = [];
$scope.group[0].users = [];
$scope.group[0].name = '';
$scope.group[0].description = '';
}
};
function getUserGroup(id) {
userGroupService.getbyid(id).then(function (info) {
if (info !== undefined && info.id === id) {
$scope.group[0].id = info.id;
$scope.group[0].name = info.name;
$scope.group[0].description = info.description;
console.log($scope.group);
// $rootScope.$broadcast('rCube-user-mgt-users-list', info.id);
// $rootScope.$broadcast('rCube-user-mgt-permissions-list', info.id);
}
else {
}
}).catch(function (exception) {
console.error(exception);
});
}
$scope.init();
});
})(angular.module('r-cube-user-mgt.user-group'));
I have two custom directives in the first block of code for user permissions and users. The group scope that i pass with the directive does not contain the values i put in the getUserGroup(id) function. The group name and group description shows up so the scope.group in the controller is filled, however thats not the case once i pass it to my directives. here is the directives code as well :
permissions list :
(function (module) {
'use strict';
module.directive('usermgrPermissionList', function () {
return {
restrict: 'E',
scope:{
group: '='
},
controller: function ($scope, permissionService) {
$scope.updatedPermissions=[];
console.log($scope.group); //it doesnt have the values from the controller ..
if (!$scope.group.hasOwnProperty('permissions')) {
$scope.group.permissions = [];
}
function getData() {
console.log("inside getDAta for permission list" + $scope.group.id;
permissionService.getPermissionsFiltered($scope.group.id).then(function (info) {
if (info && info.length > 0) {
console.log(info);
$scope.group.permissions = info.map(function (a, index, array) {
return {
id: a.id,
name: a.name,
description: a.description,
assigned: a.assigned
};
});
}
}).catch(function (exception) {
console.error(exception);
});
} //end of getData()
$scope.init = function () {
getData();
};
$scope.init();
},
templateUrl: 'r-cube-user-mgt/permission/list/list.tpl.html'
};
});
})(angular.module('r-cube-user-mgt.permission'));
can anyone help?
you cannot assign property to an array like this $scope.group.id = 0;
either make $scope.group object
$scope.group = {};
or add properties to an index
$scope.group = [];
$scope.init = function () {
if ($routeParams.hasOwnProperty('id')) {
//edit mode
// $scope.trans.heading = 'Edit Release';
// $scope.trans.saveBtn = 'Save';
var id = parseInt($routeParams.id);
getUserGroup(id);
} else {
$scope.group[0].id = 0;
$scope.group[0].permissions = [];
$scope.assignedPermissions = [];
$scope.enrolledUsers = [];
$scope.group[0].users = [];
$scope.group[0].name = '';
$scope.group[0].description = '';
}
};
So I solved the issue by adding broadcast to send the id when the directive loads. This worked!
in the Group controller i add broadcast and send the group.id
function getUserGroup(id) {
userGroupService.getbyid(id).then(function (info) {
if (info !== undefined && info.id === id) {
$scope.group.id = info.id;
$scope.group.name = info.name;
$scope.group.description = info.description;
console.log($scope.group);
$rootScope.$broadcast(rCubeTopics.userMgtPermissionLoadData, $scope.group.id);
}
}).catch(function (exception) {
console.error(exception);
});
}
and in the permission directive get that broadcast :
$scope.$on(rCubeTopics.userMgtPermissionLoadData, function (event, id) {
console.log($scope.group.id);
getData();
});

basic $scope connection with model

Its my code:
.controller("GetAllAuthors", function ($scope, $http) {
$http.get('http://localhost:8080/authors')
.then(function (response) {
$scope.authors = response.data;
});
$scope.edit = function (index) {
for (var i = 0; i < $scope.authors.length; i++) {
if ($scope.authors[i].id == index) {
$scope.object = $scope.authors[i];
break;
}
}
}
})
Html view:
<tbody ng-repeat="author in authors">
<td><input type="button" ng-click="edit(author.id)" value="Edit"/></td>
<div ng-controller="GetAllAuthors">
{{object.id}} // <--- doesn't display it
</div>
It's not working. I can't use date binding with my object. How fix it?
You need to put http inside edit method.
.controller("GetAllAuthors", function ($scope, $http) {
$scope.edit = function (index) {
$http.get('http://localhost:8080/authors')
.then(function (response) {
$scope.authors = response.data;
for (var i = 0; i < $scope.authors.length; i++) {
if ($scope.authors[i].id == index) {
$scope.object = $scope.authors[i];
break;
}
}
});
}
})
Try this
Initialize $scope.object outside the function.

how to implement ng-model value from another view in ionic

I want to display ng-model value from page to input in another page
I Want display selected issue from issues page to contact page
Issue Controller
.controller('IssueCtrl', function($scope, $http) {
$http.get('api/issues').then(function(resp) {
console.log('Success', resp);
$scope.issues = resp.data;
}, function(err) {
console.error('ERR', err);
$scope.issues = err;
});
})
Contact Controller
.factory('Post', function($resource) {
return $resource('api/add_new_order',{problem: "#problem"});
})
.controller('ContactCtrl', function($scope, Post) {
// Get all posts
$scope.posts = Post.query();
// Our form data for creating a new post with ng-model
$scope.postData = {};
$scope.newPost = function() {
var post = new Post($scope.postData);
post.$save();
}
$scope.issues = {};
$scope.answer = function(){
console.log($scope.issues.name);
}
})
Issue View
<ion-list ng-repeat="item in issues">
<ion-radio ng-model="issues.name" ng-value="'{{item.issue}}'">
{{item.issue}}
</ion-radio>
</ion-list>
Contact View
<form ng-submit="newPost()">
<label class="item item-input">
<span class="input-label">Problem :</span>
<input type="text" name="problem" ng-model="postData.problem">
</label>
</form>
Your API requests should be on independent services, so they can be accessed by any controller.
As you seen to know how a factory works, I will give you an example.
.factory('IssuesService', function($http) {
var issues = [];
return {
all: function() {
return $http.get('api/issues')
.then(function(data){ // Optional callback inside service
issues = data;
});
}
}
})
.controller('ContactCtrl', function($scope, Post, IssuesService) {
...
$scope.issues = [];
IssuesService.all().then(function(data){
$scope.issues = data;
})
...
})
.controller('IssueCtrl', function($scope, $http) {
IssuesService.all()
.then(function(resp) {
console.log('Success', resp);
$scope.issues = resp.data;
}, function(err) {
console.error('ERR', err);
$scope.issues = err;
});
})

How to save data values from form in angularjs using fat free framework

I am trying to save data in sql using fat free framework. i used front end in angularjs. i send data using angular ng-submit button. ajax Post data but not get in fat free please solve this problem. i am new in fat free.
here is my html code:
<form id="userRegister" name="registration" ng-submit="register1(formData)" ng-controller="Ctrl1">
<div class="sf-steps-form sf-radius">
<div class="sf_columns column_3">
<input ng-model="formData.email" id="email" type="email" name="email" placeholder="Email*" data-required="true" >
</div>
<div class="sf_columns column_3">
<input ng-model="formData.password" id="password" type="password" name="password" placeholder="Secret Word*" data-required="true" >
</div>
</div>
<button type="submit" id="sf-next" class="sf-button">Save</button>
</form>
here is my app.js code:
sampleApp.controller("Ctrl1", function($scope, $http) {
$scope.formData = {};
$scope.register1 = function() {
console.log($scope.formData);
$http({
method : 'POST',
url : 'addstep',
data : $scope.formData,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
if (data.errors) {
$scope.errorEmail = data.errors.email;
$scope.errorPassword = data.errors.password;
} else {
$scope.message = data.message;
}
});
};
});
here is my idex.php fat free framework code:
$f3->route('GET|POST /addstep',
function($f3) {
//print_r($f3);
$users = new DB\SQL\Mapper($f3->get('DB'),'user');
$users->copyFrom('POST');
$users->save();
$f3->set('content','step1.htm');
echo View::instance()->render('layout.htm');
}
);
The ajax post data properly but not save in db please help.
Check $f3->get('BODY');
You might need to json_decode;
Most likely the data is sent via PUT
I actually just dealt with this on an application using f3 and angular. If you haven't figured it out I have been pretty successful with this:
I have an angular $http service:
angular.module('myApp')
.service('apiConnector', function apiConnector($http) {
var apiBase = '';
var obj = {};
obj.get = function(q) {
return $http.get(apiBase + q).then(function(results) {
return results.data;
});
};
obj.post = function(q, object) {
return $http.post(apiBase + q, object).then(function(results) {
return results.data;
});
};
obj.put = function(q, object) {
return $http.put(apiBase + q, object).then(function(results) {
return results.data;
});
};
obj.delete = function(q) {
return $http.delete(apiBase + q).then(function(results) {
return results.data;
});
};
return obj;
});
Then I use this service in my angular controllers like so:
angular.module('myApp')
.controller('homeController',function($scope, $state, $stateParams, $timeout, apiConnector){
$scope.user = {};
apiConnector.get('/api/users/'+$stateParams.id)
.then(function(res){
if (res.success) {
$scope.user = res.data;
}
},function(err){
console.log(err);
});
$scope.updateUser = function(user) {
apiConnector.post('/api/users/'+$stateParams.id,user)
.then(function(res){
if (res.success) {
alert('updated');
}
}, function(err){
console.log(err);
});
};
});
Lastly the f3 controller. I am using [maps] for my routes to get a truly restful interface, and my routes use an #id param. I collect data like so:
class Item {
function get($app,$params) {
$id = $params['id'];
$user = new \Models\User();
$user->load(array('id = ?',$id));
echo json_encode($user->cast());
}
function post($app,$params) {
$POST = json_decode(file_get_contents('php://input'));
$id = $params['id'];
$user = new \Models\User();
$user->load(array('id = ?',$id));
$user->copyfrom($POST);
$user->touch('created');
$user->save();
echo json_encode(array('message' => 'Successfully updated user!'));
}
function put() {}
function delete() {}
}
Hope that helps!

Resources