file upload with other form data getting file undefined angularjs - angularjs

'use strict';
var app = angular.module('myApp', []);
app.directive('fileModel', ['$parse', function($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function() {
scope.$apply(function() {
modelSetter(scope, element.files[0]);
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
app.service('fileUpload', ['$http', function($http) {
this.uploadFileToUrl = function(data, file, uploadUrl) {
var fd = new FormData();
fd.append('name', data.name);
fd.append('phone', data.phone);
fd.append('experience', data.experience);
fd.append('email', data.email);
fd.append('position', data.position);
fd.append('resume', file);
var promise = $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
});
promise.then(function(response) {
var request = response.data;
if (request.success == "true") {
alert("Thank you for getting in touch with Mohar");
var inst = $('[data-remodal-id=modal]').remodal();
inst.close();
$scope.userForm.$setPristine();
$scope.userForm.$setUntouched();
} else {
alert("Please try after sometime");
window.location.href = 'career.html';
}
});
}
}]);
app.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload) {
$scope.val1 = 'Sr. Python Developer';
$scope.val2 = 'Jr. Python Developer';
$scope.val3 = 'Sr. UI Developer';
$scope.val4 = 'Jr. UI developer';
$scope.val5 = 'Sr. Android Developer';
$scope.val6 = 'Jr. Android Developer';
$scope.val7 = 'Sr. Tester';
$scope.val8 = 'Jr. Tester';
$scope.val9 = 'Sr. Devops Engineer';
$scope.val10 = 'Graphic designer';
$scope.applyJob = function(val) {
$scope.name = '';
$scope.phone = '';
$scope.experience = '';
$scope.email = '';
$scope.position = val
console.log('clicked', $scope.position);
}
$scope.uploadFile = function() {
var data = {
'name': $scope.name,
'phone': $scope.phone,
'experience': $scope.experience,
'email': $scope.email,
'position': $scope.position
}
var file = $scope.myFile;
console.log('file is ', $scope.myFile)
var uploadUrl = "career.php";
fileUpload.uploadFileToUrl(data, file, uploadUrl);
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.10/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<form name="userForm" class="job-form" autocomplete="off">
<div class="row">
<div class="form-group">
<input type="text" class="form-control form-control-payment" ng-model="name" name="name" id="name" ng-pattern="/^[a-zA-Z ]*$/" ng-minlength="1" ng-maxlength="20" placeholder="Full Name" required />
<div ng-show="userForm.name.$dirty && userForm.name.$invalid || userForm.name.$touched">
<p ng-show="userForm.name.$error.required">Please enter name</p>
<p ng-show="userForm.name.$error.pattern">Please enter valid name</p>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control form-control-payment" ng-model="phone" name="phone" id="number" ng-pattern="/^[0-9]*$/" ng-minlength="10" ng-maxlength="10" placeholder="Phone Number" required />
<div ng-show="userForm.phone.$dirty && userForm.phone.$invalid || userForm.phone.$touched">
<p ng-show="userForm.phone.$error.required">Please enter contact number</p>
<p ng-show="userForm.phone.$error.minlength">Please enter minimum 10 digit</p>
<p ng-show="userForm.phone.$error.maxlength || userForm.phone.$error.pattern">Please enter valid contact number</p>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control form-control-payment" ng-model="experience" name="experience" id="experience" ng-pattern="/^[0-9]*$/" placeholder="Experience" required />
<div ng-show="userForm.experience.$dirty && userForm.experience.$invalid || userForm.experience.$touched">
<p ng-show="userForm.experience.$error.required">Please enter total experience</p>
<p ng-show="userForm.experience.$error.pattern">Please enter only numbers</p>
</div>
</div>
<div class="form-group">
<input type="email" class="form-control form-control-payment" name="email" ng-model="email" id="email" placeholder="E-mail" required />
<div ng-show="userForm.email.$dirty && userForm.email.$invalid || userForm.email.$touched">
<p ng-show="userForm.email.$error.required">Email is required.</p>
<p ng-show="userForm.email.$error.email">Invalid email address.</p>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control form-control-payment" id="position" ng-model="position" ng-readonly="true" placeholder="Position" required />
<!-- <input type="text" class="form-control" id="position" placeholder="e.g: UI DEVELOPER" required> -->
</div>
<div class="form-group">
<input type="file" class="form-control form-control-payment" fileModel="myFile" id="resume" required>
</div>
<button type="submit" class="btn btn-submit pull-right" ng-click="uploadFile()">Submit</button>
</div>
<!-- ng-disabled="userForm.$invalid" -->
</form>
</div>
hello, I am using angularjs for validation & HTTP call. I want to post a file with some other form data like name, email, phone, experience, position etc.when I click on submit button It send an empty file. I don't understand what is wrong with this code please help i am new to angularjs. thank you in advance.

In the fileModel directive, delete the erroneous line:
app.directive('fileModel', ['$parse', function($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function() {
scope.$apply(function() {
̶m̶o̶d̶e̶l̶S̶e̶t̶t̶e̶r̶(̶s̶c̶o̶p̶e̶,̶ ̶e̶l̶e̶m̶e̶n̶t̶.̶f̶i̶l̶e̶s̶[̶0̶]̶)̶;̶
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
In the template, instantiate the directive with kebab-case not camelCase:
<input type="file" class="form-control form-control-payment"
̶f̶i̶l̶e̶M̶o̶d̶e̶l̶=̶"̶m̶y̶F̶i̶l̶e̶"̶
file-model="myFile"
id="resume" required>
For more information, see AngularJS Developer Guide - Directive Normalization

Related

unable to get data from html in angular js

in this code of HTML, we get input text value and send to the Angular controller
so they get to work as defined in code.
<div class="row" ng-controller="RegionController">
<div class="col-lg-12" >
<div class="hpanel">
<div class="panel-heading">
<!-- <div panel-tools></div> -->
<h2>Region Master Entry</h2>
</div>
<div class="panel-body">
<!--change form name,and submit controller name-->
<form role="form">
<div class="form-group">
<label class="col-sm-2 control-label">Region Name</label>
<div class="col-sm-10">
<input type="text" placeholder="please enter Region name" class="form-control m-b" required name="Region Name" ng-model="formRegionData.region_name" >
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Region Code</label>
<div class="col-sm-10">
<input type="text" placeholder="please enter Region code" class="form-control m-b" required name="Region Code" ng-model="formRegionData.region_code">
</div>
</div>
<div class="form-group">
<div class="col-sm-3">
<label>Active</label>
</div>
<div class="checkbox checkbox-success col-sm-9">
<input id="checkbox3" type="checkbox" checked="" ng-model="formRegionData.status">
<label for="checkbox3">
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-4"></div>
<div class="col-sm-8">
<button class="btn btn-sm btn-primary btn-xl text-right" type="submit" ng-click="createRegion()"><strong> Save Region </strong></button>
</div>
</div>
{{formRegionData | json}}
</form>
</div>
</div>
</div>
</div>
"{{formRegionData | json}}" this will return in HTML input text result of but not send data to the controller
in Controller the code is written as
.controller('RegionController', function( $scope , regionService) {
$scope.createRegion = function() {
debugger;
vm.processing = true;
vm.message = '';
console.log(formRegionData);
regionService.SaveRegion( formRegionData )
.then(function(data) {
debugger;
//console.log(data);
//.success(function(data) {
vm.processing = false;
vm.storyData = {};
vm.message = data.message;
});
}
})
and my service to work according to Controller
.factory('regionService',function($http ){
var regionFactory = {};
regionFactory.SaveRegion = function(formRegionData) {
debugger;
return $http.post('/api/region/', formRegionData);
}
return regionFactory;
});
You have missed $scope
$scope.createRegion = function() {
debugger;
$scope.processing = true;
$scope.message = '';
console.log($scope.formRegionData);
regionService.SaveRegion($scope.formRegionData )
.then(function(data) {
debugger;
//console.log(data);
//.success(function(data) {
$scope.processing = false;
$scope.storyData = {};
$scope.message = data.message;
});
}
})
and remove ng-click="createRegion()" in your button control and add this code in your form tag by ng-submit. like,
<form ng-submit="createRegion()" role="form">
You have missed of $scope in form region data
Here is the link Jsfiddle
JS
angular.module('myApp', ['ngStorage'])
.controller('RegionController', function($scope, regionService) {
var vm = this;
$scope.createRegion = function() {
debugger;
vm.processing = true;
vm.message = '';
regionService.SaveRegion($scope.formRegionData)
.then(function(data) {
debugger;
//console.log(data);
//.success(function(data) {
vm.processing = false;
vm.storyData = {};
vm.message = data.message;
});
}
}).factory('regionService', function($http) {
var regionFactory = {};
regionFactory.SaveRegion = function(formRegionData) {
debugger;
return $http.post('/api/region/', formRegionData);
}
return regionFactory;
});

Connect Express nodemailer with Angular

I'm trying to make a contact form, and the server side is working pretty well. But I don't know how to connect Angular to the html form and send it with Express. Any would appreciate any help.
My Express
router.get('/sendQuote', function(req, res) {
var data = req.query;
var mailOptions = {
from: 'planacte#gmail.com', // sender address
name: data.contactName,
email: data.contactEmail,
to: data.email, // list of receivers
subject: "Request for a Quote from " + data.contactName, // Subject line
text: data.contactMsg, // plaintext body
html: '<p> email: ' + data.contactEmail +
'</p><p> phone: ' + data.contactPhone + '</p><br>'
+data.contactMsg // html body
};
console.log(mailOptions)
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
});
So, my html:
<form id="contact" class="contact-form" ng-submit="sendMail()" novalidate>
<div class="message"></div>
<div class="col-md-5 col-sm-5 col-xs-12 animated hiding" data-animation="slideInLeft">
<div class="form-group">
<input type="text" name="name" class="nameform form-control input-lg" placeholder="name" ng-model="contactName" required>
</div>
<div class="form-group">
<input type="email" name="email" class="emailform form-control input-lg" placeholder="email" ng-model="message.contactEmail" required>
</div>
<div class="form-group">
<input type="text" name="phone" class="phoneform form-control input-lg" placeholder="phone" ng-model="message.contactPhone">
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<div class="form-group">
<textarea name="message" class="messageform form-control input-lg" placeholder="custom text" ng-model="message.contactMsg" required></textarea>
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<input type="submit" class="btn btn-custom up form-button" value="Send Message">
And the main problem is here, how to glue Angular with HTML and Express. I can send emails, but get undefined in the fields of Name, Email and so on. :
app.controller('MainCtrl', ['$scope', '$interval', '$http', '$location', '$anchorScroll',
function($scope, $interval, $http, $location, $anchorScroll) {
$scope.sendMail = function () {
$scope.message = {};
$http.get('/send/sendQuote', $scope.message).
success(function(data, status, headers, config) {
// $scope.message = data.message;
console.log($scope.message)
});
}
}]);
I think you should start by making this request a POST and not a GET request.
router.post('/sendQuote', function(req, res) {
var data = req.body;
var mailOptions = {
from: 'planacte#gmail.com', // sender address
name: data.contactName,
email: data.contactEmail,
to: data.email, // list of receivers
subject: "Request for a Quote from " + data.contactName, // Subject line
text: data.contactMsg, // plaintext body
html: '<p> email: ' + data.contactEmail +
'</p><p> phone: ' + data.contactPhone + '</p><br>'
+data.contactMsg // html body
};
console.log(mailOptions)
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
res.send(200); // let the client know it sent ok.
});
Now, let's take a look at your Angular code. It seems you want the object $scope.message to hold your form fields data. You should define this as an object at the beginning of your controller.
app.controller('MainCtrl', ['$scope', '$interval', '$http', '$location', '$anchorScroll',
function($scope, $interval, $http, $location, $anchorScroll) {
$scope.message = {};
$scope.sendMail = function () {
//$scope.message = {}; -- this was clearing the object
$http.post('/send/sendQuote', $scope.message).
success(function(data, status, headers, config) {
// you can clear $scope.message if you want here
// $scope.message = data.message;
console.log($scope.message)
});
}
}]);
HTML had one ng-model not binding to the message object:
<form id="contact" class="contact-form" ng-submit="sendMail()" novalidate>
<div class="message"></div>
<div class="col-md-5 col-sm-5 col-xs-12 animated hiding" data-animation="slideInLeft">
<div class="form-group">
<input type="text" name="name" class="nameform form-control input-lg" placeholder="name" ng-model="message.contactName" required>
</div>
<div class="form-group">
<input type="email" name="email" class="emailform form-control input-lg" placeholder="email" ng-model="message.contactEmail" required>
</div>
<div class="form-group">
<input type="text" name="phone" class="phoneform form-control input-lg" placeholder="phone" ng-model="message.contactPhone">
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<div class="form-group">
<textarea name="message" class="messageform form-control input-lg" placeholder="custom text" ng-model="message.contactMsg" required></textarea>
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<input type="submit" class="btn btn-custom up form-button" value="Send Message">

Reset form on submit

I am submitting a form and then making all the field empty but it's not working. Form is getting submitted successfully but the fields are not getting reset. I am using angular-material for styling. Updated controller.
Html
<form name="myform">
<md-input-container>
<label for="name">Contact Name</label>
<input type="text" md-maxlength="20" required="" md-no-asterisk name="name" ng-model="info.name" md-autofoucs>
<div ng-messages="myform.name.$error" role="alert">
<div ng-message="required">This is required.</div>
<div ng-message="md-maxlength">The name has to be less than 20 characters long.</div>
</div>
</md-input-container>
<md-input-container>
<label for="phone">Phone Number</label>
<input type="text" name="phone" required md-no-asterisk ng-model="info.phone">
<div ng-messages="myform.phone.$error">
<div ng-message="required">This is required.</div>
</div>
</md-input-container>
<md-input-container>
<label for="email">Email</label>
<input type="text" name="email" ng-model="info.email">
</md-input-container>
<md-input-container>
<md-button class="md-primary" ng-click="saveit(info)">Save</md-button>
<md-button class="md-primary">Cancel</md-button>
</md-input-container>
</form>
**Function in Controller**
angular.module('contact', ['ui.router', 'ngMaterial', 'templates','ngMessages'])
.config(['$mdThemingProvider', '$stateProvider', function ($mdThemingProvider, $stateProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('blue')
.accentPalette('orange');
$stateProvider
.state('home', {
url: '',
templateUrl: 'templates/home.html',
controller: 'MainCtrl as vm'
});
}]).controller('MainCtrl', function ($scope, $mdSidenav,$mdDialog,$mdToast, contacts) {
var vm = this;
$scope.searchText ="";
$scope.toggleSidenav = function(){
$mdSidenav('left').open();
};
contacts.getall().then(function(response){
console.log(response.data);
$scope.people = response.data;
});
$scope.saveit = function(detail, myform){
if (!detail.name || !detail.phone) { return ;}
contacts.add({
name: detail.name,
phone: detail.phone,
email: detail.email
});
$mdToast.show(
$mdToast.simple()
.content("ContactAdded!")
.position('top, right')
.hideDelay(2000)
);
$scope.people.push(detail);
$scope.info = {};
$scope.myform.$setPristine();
$scope.myform.$setUntouched();
};
$scope.showConfirm = function(ev, person) {
var confirm = $mdDialog.confirm()
.title('Are you sure?')
.ariaLabel('Lucky day')
.targetEvent(ev)
.ok('Please delete it!')
.cancel('I want to keep it.');
$mdDialog.show(confirm).then(function() {
contacts.deletethis(person.id).then(function(){
$mdToast.show(
$mdToast.simple()
.content("Deleted!")
.position('top, right')
.hideDelay(2000)
);
});
var index = $scope.people.indexOf(person);
$scope.people.splice(index,1);
}, function() {
$scope.status = 'You decided to keep your debt.';
});
}; });
<form name="myform">
<input type="text" ng-model="info.name">
<input type="text" ng-model="info.phone">
<input type="text" ng-model="info.email">
</form>
app.controller('MainCtrl', function($scope) {
$scope.info = {}; // name, phone, email
$scope.saveit = function() {
$scope.info.name = ''; // reset name
$scope.info.phone= ''; // reset phone
$scope.info.email= ''; // reset email
// reset form and disable error messages
$scope.myform.$setPristine();
$scope.myform.$setUntouched();
};
});
You are not using $scope and this for controller correctly. You can use $scope or controller as syntax to bind your scope with view.
I suggest you to read more about it here.
Update your saveit() function inside controller as below:
app.controller('MainCtrl', function($scope, $mdSidenav, $mdDialog, $mdToast) {
var vm = this;
vm.info = {};
//your rest the code
vm.saveit = function() {
//do your operations here
vm.info = {};
};
});
Update your html page as below:
<div ng-controller="MainCtrl as vm">
<form name="myform">
<md-input-container>
<label for="name">Contact Name</label>
<input type="text" ng-maxlength="20" required md-no-asterisk name="name" ng-model="vm.info.name" md-autofoucs>
</md-input-container>
<md-input-container>
<label for="phone">Phone Number</label>
<input type="text" name="phone" required md-no-asterisk ng-model="vm.info.phone">
</md-input-container>
<md-input-container>
<label for="email">Email</label>
<input type="text" name="email" ng-model="vm.info.email">
</md-input-container>
<md-input-container>
<md-button class="md-primary" ng-click="vm.saveit()">Save</md-button>
<md-button class="md-primary">Cancel</md-button>
</md-input-container>
</form>
</div>
Give $setPristine to reset the form after saving.
$scope.myform.$setPristine();
Another approach
app.controller('MainCtrl', function($scope, $mdSidenav, $mdDialog, $mdToast) {
var vm = this;
vm.info = {};
vm.saveit = function($event)
{
var form = angular.element($event.target).parent("form")[0];
if (form !== undefined) form.reset();
};
});
<div ng-controller="MainCtrl as vm">
<form name="myform">
<md-input-container>
<label for="name">Contact Name</label>
<input type="text" ng-maxlength="20" required md-no-asterisk name="name" ng-model="vm.info.name" md-autofoucs>
</md-input-container>
<md-input-container>
<label for="phone">Phone Number</label>
<input type="text" name="phone" required md-no-asterisk ng-model="vm.info.phone">
</md-input-container>
<md-input-container>
<label for="email">Email</label>
<input type="text" name="email" ng-model="vm.info.email">
</md-input-container>
<md-input-container>
<md-button class="md-primary" ng-click="vm.saveit($event)">Save</md-button>
<md-button class="md-primary">Cancel</md-button>
</md-input-container>
</form>
</div>
The answer below is missing one line of code to work properly
You can check the answer from another question right here:
https://stackoverflow.com/a/40267630/4767208

How to track two dimentional array data using Angularjs

I am new to Angularjs. I learned some basic concepts and I started developing a form. According to my requirements, I have to give 4 textboxes and if user wants wants more he adds another 4 textboxes. Meanwhile, I am unable to track the entered details.
// create angular app
var validationApp = angular.module('validationApp','');
// create angular controller
validationApp.controller('mainController', function($scope) {
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.showChoiceLabel = function (choice) {
return choice.id === $scope.choices[0].id;
};
$scope.removeChoice = function() {
if($scope.choices.length>1){
var newItemNo = $scope.choices.length-1;
$scope.choices.pop();
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="validationApp" ng-controller="mainController">
<div class="form-group" data-ng-repeat="choice in choices">
<label for="choice" ng-show="showChoiceLabel(choice)">Family Details</label>
<input type="text" ng-model="choice.name" name="id.family_name" class="form-control" placeholder="Enter Family Memeber Name" size="20">
<input type="text" ng-model="choice.relation" name="id.family_relation" class="form-control" placeholder="Enter Relation" size="15">
<input type="text" ng-model="choice.age" name="id.family_age" class="form-control" placeholder="Enter Age" size="5">
<input type="text" ng-model="choice.qualification" name="id.family_qualification" class="form-control" placeholder="Enter Qualification" size="15">
<br/><button ng-show="$last" ng-click="addNewChoice()" class="btn btn-success">Add another member</button>
<button ng-show="$last" ng-click="removeChoice()" class="btn btn-danger">Remove field</button>
</div>
</div>
You have had an error in your initialisation of your app. The empty array in angular.module('validationApp', []). This array is the list of modules myApp depends on:
var validationApp = angular.module('validationApp',[]);
Further information in the docs.
// create angular app
var validationApp = angular.module('validationApp', []);
// create angular controller
validationApp.controller('mainController', function($scope) {
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({id:'choice' + newItemNo});
};
$scope.showChoiceLabel = function(choice) {
return choice.id === $scope.choices[0].id;
};
$scope.removeChoice = function() {
if($scope.choices.length > 1) {
var newItemNo = $scope.choices.length - 1;
$scope.choices.pop();
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="validationApp" ng-controller="mainController">
<div class="form-group" data-ng-repeat="choice in choices">
<label for="choice" ng-show="showChoiceLabel(choice)">Family Details</label>
<input type="text" ng-model="choice.name" name="id.family_name" class="form-control" placeholder="Enter Family Memeber Name" size="20">
<input type="text" ng-model="choice.relation" name="id.family_relation" class="form-control" placeholder="Enter Relation" size="15">
<input type="text" ng-model="choice.age" name="id.family_age" class="form-control" placeholder="Enter Age" size="5">
<input type="text" ng-model="choice.qualification" name="id.family_qualification" class="form-control" placeholder="Enter Qualification" size="15">
<br/><button ng-show="$last" ng-click="addNewChoice()" class="btn btn-success">Add another member</button>
<button ng-show="$last" ng-click="removeChoice()" class="btn btn-danger">Remove field</button>
</div>
</div>

angularfire using $loaded how to access data in a directive

This post is a follow up of
this
(the goal is set img to visibily and set the src)
html
<form class="form-horizontal" role="form" name="form" data-ng-submit="add()">
<div class="form-group">
<input type="text" name="title" tabindex="1" class="form-control" placeholder="{{ 'items.form.title' | translate }}" data-ng-model="item.title" required="required" data-ng-minlength="3" data-ng-maxlength="25" user-feedback />
</div>
<div class="form-group">
<input type="text" name="ingredients" tabindex="2" class="form-control" placeholder="{{ 'items.form.ingredients' | translate }}" data-ng-model="item.ingredients" required="required" ng-pattern="/^\w(\s*,?\s*\w)*$/" user-feedback />
</div>
<div class="form-group">
<input type="text" name="price" tabindex="3" class="form-control" placeholder="{{ 'items.form.price' | translate }}" data-ng-model="item.price" required="required" data-smart-float user-feedback />
</div>
<div class="form-group">
<button type="button" tabindex="4" class="btn btn-default btn-lg" item="item" data-uploader>{{ 'items.form.upload' | translate }}</button>
<input type="text" name="url" style="display:none;" required="required" data-ng-model="item.url" />
</div>
<div class="form-group form-no-required clearfix">
<div class="pull-right">
<button type="submit" tabindex="5" class="btn btn-primary" data-ng-disabled="form.$invalid">{{ 'items.form.submit' | translate }}</button>
</div>
</div>
</form>
js
app.controller('ItemsUpdateController', function ($scope, item, Items, $state) {
item.$loaded().then(function(data) {
$scope.item = data;
});
$scope.add = function() {console.log($scope.item);
/* Items.update(item.$id,$scope.item).then(function () {
$state.transitionTo('items');
});*/
}
});
app.directive('uploader', function() {
return {
restrict: 'A',
scope:{
item: '='
},
link: function(scope, element, attrs) {
if (window.File && window.FileReader && window.FileList && window.Blob) {
var fileElem = angular.element('<input type="file" style="display:none;">');
var imgElem = angular.element('<img src="" width="50" style="margin-left:10px;visibility:hidden;">');
element.after(fileElem);
element.after(imgElem);console.log(scope.item); //This give me undefined
/*if(scope.item.url){
imgElem.css('visibility','visible');
imgElem[0].src = scope.item.url;
}*/
fileElem.on('change',function(e){
e.stopPropagation();
var files = e.target.files;
var reader = new FileReader();
reader.onloadend = function () {
var url = reader.result;
imgElem.css('visibility','visible');
imgElem[0].src = url;
scope.$apply(function () {
scope.item.url = url;
});
}
reader.readAsDataURL(files[0]);
});
element.on('click', function(e) {
e.stopPropagation();
fileElem[0].click();
});
element.on('$destroy',function(){
element.off('click');
});
fileElem.on('$destroy',function(){
fileElem.off('change');
});
}
},
};
});
Why console.log(scope.item); give me undefined
but I can see the right values fill the form ?
and how can I get the value ?
(btw I've tried also with $timeout or $apply but both doesn't work)
I've also tried with
scope.$watch('item', function(newVal, oldVal){
console.log(newVal, oldVal);
}, true);
but I've got
[Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)"
and I don't really understand why
console.log(scope.item);// Object { $$conf={...}, $id="-J_C-q-6bIW9PBZzqpAg"
console.log(angular.equals({}, scope.item));// but this is true !
Ugly ends up
//controller
$scope.item = item;
$scope.item.$loaded().then(function(data) {
$scope.item = data;
});
//directive
if(scope.item.$id){
scope.item.$loaded().then(function(data) {
imgElem.css('visibility','visible');
imgElem[0].src = data.url;
});
if anyone have got a better solution is welcome :)
}

Resources