Upload image and save in local storage using angularjs - angularjs

I want to have a button on my page from where I can upload an image from local system and then I want to save that image in my local storage.
I am keen to learn angularjs here.

You'd want to encode the image as a base 64 string and store that in local storage.
See this answer for an example of how to convert the image to a base 64 string. toDataURL() returns a string, which you can then store the same way you would normally store a string in a JSON object.
To display the image, you use something like this:
<img src="data:image/jpeg;base64,blahblahblah"></img>
where blahblahblah is the string returned.

Follow below code for upload and save image using AngularJS
Create index.php file and initialize app and create AngularJS controller.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<div>
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
</div>
</body>
</html>
After this, Create app.js and write code to upload image using AngularJS.
var myApp = angular.module('myApp', []);
myApp.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[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' + JSON.stringify(file));
var uploadUrl = "post.php";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
After this, Create post.php file to upload file into storage.
<?php $upload_dir = "images/";
if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png", "gif");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg")) && in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0){
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
} else {
if (file_exists($upload_dir.$_FILES["file"]["name"])) {
echo 'File already exist';
} else {
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$filename = rand().$_FILES['file']['name'];
$targetPath = $upload_dir.$filename; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo 'success';
}
}
}
} ?>
Create images folder.
Hope this will help you. For reference: http://jsfiddle.net/JeJenny/ZG9re/

Related

How to bind data in 'value' attribute of <input tag> to NET core MVC model using angular

I’ve been playing around with Upload file - Streaming method. The original code, here:
https://github.com/aspnet/Docs/tree/master/aspnetcore/mvc/models/file-uploads/sample/FileUploadSample
However, I’m trying to get the data in the value attribute of <input value=” ”> using Angular, the idea is that I can POST the value into my MVC model instead of whatever is typed by the user (as in the original code). So, I have done this change to the input value property.
Streaming/Index.cshtml:
<div ng-app="myApp">
<div ng-controller="myCtrl">
..
<input value="#Model.name” type="text" name="Name" ng-model="name"/>
..
<button ng-click="createUser()">Create User</button>
..
</div>
</div>
#section scripts{
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="~/js/app.js"></script>
}
However, with Angular code running under app.js, the following piece of code actually fails with status code 400. This is because the passed value is “” and not the data under of value attribute of the HTML input tag.
App.js:
var User = (function () {
function User(name) {
this.name = name;
}
return User;
}());
var myApp = angular.module('myApp', []);
myApp.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[0].files[0]);
});
});
}
};
}]);
myApp.service('userService', ['$http', function ($http) {
this.createUser = function(user) {
var fd = new FormData();
fd.append('name', user.name);
return $http.post('/streaming/upload', fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
});
};
}]);
myApp.controller('myCtrl', ['$scope', 'userService', function ($scope, userService) {
$scope.createUser = function () {
$scope.showUploadStatus = false;
$scope.showUploadedData = false;
var user = new User($scope.name);
userService.createUser(user).then(function (response) { // success
if (response.status == 200) {
$scope.uploadStatus = "User created sucessfully.";
$scope.uploadedData = response.data;
$scope.showUploadStatus = true;
$scope.showUploadedData = true;
$scope.errors = [];
}
},
function (response) { // failure
$scope.uploadStatus = "User creation failed with status code: " + response.status;
$scope.showUploadStatus = true;
$scope.showUploadedData = false;
$scope.errors = [];
$scope.errors = parseErrors(response);
});
};
}]);
function parseErrors(response) {
var errors = [];
for (var key in response.data) {
for (var i = 0; i < response.data[key].length; i++) {
errors.push(key + ': ' + response.data[key][i]);
}
}
return errors;
}
The solution must be a simple one, but after much research, I haven’t been able to find out how to modify it to make the data in the value=’’” attribute being passed across. This might be a stupid question but a headache for me however since I’m a total newbie regarding Angular. Please have some mercy, help.
Thanks
Use the ng-init directive to initialize the model:
<input ng-init="name= #Model.name" type="text" name="Name" ng-model="name"/>

Can't post a file to a service successfully

I am trying to upload a file through Angularjs. I am hitting the service but not able to get the file on the server. I have posted my code below. Please let me know the errors/modifications in the code.
<html>
<head>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<form name="demo">
<input type = "file" file-model = "myFile"/>
<button type="submit" ng-click = "uploadFile()">upload me</button>
</form>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.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[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
console.log('file uploaded');
})
.error(function(){
console.log('file not uploaded');
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "http://172.29.5.86:8080/marketplace/inventory/testImageUpload.service";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
I can recommend you to use https://github.com/flowjs/ng-flow.
HTML
<div flow-init
flow-name="flowObject.flow" <!-- optional -->
flow-file-added="fileAdded($file)"> <!-- optional -->
<!-- Your HTML -->
<span class="btn btn-default" data-flow-btn>Select Files</span>
<span class="btn btn-primary" ng-click="uploadFiles()">Upload</span>
</div>
Controller
$scope.flowObject = {};
$scope.uploadFiles = function () {
$scope.files = $scope.flowObject.flow.files;
// some logic
myService.uploadFilesSomewhere($scope.files).then(function (response) {
// some other logic
});
};
$scope.fileAdded = function (file) {
// some logic
};

How to get AngularJS BLOB to Download PDF?

Hello everyone I am really new to developing with AngularJS and I am trying to figure out how to use BLOB to download a PDF locally to a machine. I already got it to work with a JSON and now I need a PDF. I have written some code but it doesn't seem to be working.
html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.center {
position: absolute;
left: 50%;
bottom: 50%;
}
.btn-purple {
background-color: rgb(97, 34, 115);
width: 100px;
}
</style>
<meta charset="UTF-8">
<title></title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="center" ng-controller="jsonController" ng-app="app">
<a style="color: white;" ng-href="{{ fileUrl }}" download="{{fileName}}">
<button type="button" class="btn btn-purple">{{fileName}}</button>
</a>
</div>
<div class="center" ng-controller="pdfController" ng-app="app">
<a style="color: white;" ng-href="{{ fileUrl }}" download="{{fileName}}">
<button type="button" class="btn btn-purple">{{fileName}}</button>
</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/javascript-canvas-to-blob/3.1.0/js/canvas-to-blob.js"></script>
<script src="app.js"></script>
</body>
</html>
controller.js
var app = angular.module('app', []);
app.config(['$compileProvider', function ($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(|blob|):/);
}]);
app.controller('jsonController', function ($scope, $window, $http, $log) {
$http.get('data.json')
.success(function (info) {
var data = angular.toJson(info, true);
data = data.replace(/\n/g, "\r\n")
console.log(data)
var blob = new Blob([data], {type: "octet/stream"}),
url = $window.URL || $window.webkitURL;
$scope.fileUrl = url.createObjectURL(blob);
$scope.schemaName = "test"
$scope.fileName = $scope.schemaName + ".json"
})
});
app.controller("pdfController", function ($scope, $http, $log, $sce) {
$http.get('data.json' + $stateParams.id,
{responseType: 'arraybuffer'})
.success(function (response) {
var file = new Blob([(response)], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
});
});
Possible Try-
HTML:
<button ng-click="downloadPdf()" >Download PDF</button>
JS controller:
'use strict';
var app = angular.module('app')
.controller('ctrl', function ($scope, MathServicePDF) {
$scope.downloadPdf = function () {
var fileName = "file_name.pdf";
var a = document.createElement("a");
document.body.appendChild(a);
ServicePDF.downloadPdf().then(function (result) {
var file = new Blob([result.data], {type: 'application/pdf'});
var fileURL = window.URL.createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
});
};
});
JS services:
app.factory('ServicePDF', function ($http) {
return {
downloadPdf: function () {
return $http.get('api/my-pdf', { responseType: 'arraybuffer' }).then(function (response) {
return response;
});
}
};
});
Happy Helping!
Tested with large files (> 1.5 GB) on
Firefox 56.0
Safari 11.0
Use the following in your angular controller:
$scope.download = function() {
$http({
method: 'GET',
url: fileResourceUrl,
responseType: 'blob'
}).then(function(response) {
var blob = response.data;
startBlobDownload(blob, "largedoc.pdf")
});
};
function startBlobDownload(dataBlob, suggestedFileName) {
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
// for IE
window.navigator.msSaveOrOpenBlob(dataBlob, suggestedFileName);
} else {
// for Non-IE (chrome, firefox etc.)
var urlObject = URL.createObjectURL(dataBlob);
var downloadLink = angular.element('<a>Download</a>');
downloadLink.css('display','none');
downloadLink.attr('href', urlObject);
downloadLink.attr('download', suggestedFileName);
angular.element(document.body).append(downloadLink);
downloadLink[0].click();
// cleanup
downloadLink.remove();
URL.revokeObjectURL(urlObject);
}
}
Change your responseType from responseType: 'arraybuffer'
to responseType: 'blob'
In you controller PHP
return $pdf->stream();
In you controller AngularJS
$http.post('generate', {
dateStart: $scope.ds,
dateEnd: $scope.de
},
{
responseType: 'arraybuffer'
}).then(function success(response) {
var blob = new Blob([response.data], { type: "application/pdf"});
saveAs(blob, "filename.pdf");
}, function error(error) {
$scope.recordErrors(error);
});
This code worked for me in angular 9, Yii2, while using mpdf
this._gService.download_post(`controller/action`, postData).pipe(takeUntil(this._unsubscribeAll)).subscribe(result => {
const fileURL = URL.createObjectURL(result);
// Direct print preview
// const iframe = document.createElement('iframe');
// iframe.style.display = 'none';
// iframe.src = fileURL;
// document.body.appendChild(iframe);
// iframe.contentWindow.print();
// Direct Download
const fileName = 'Patient Report';
const a = document.createElement('a');
document.body.appendChild(a);
a.href = fileURL;
a.download = fileName;
a.click();
}, error => {
// show error message
});

MEAN Stack: How to bind uploads to a mongoose model?

I´m playing around with upload forms in my MEAN Application (its a project control panel). I used this tutorial for implementing a working upload: http://markdawson.tumblr.com/post/18359176420/asynchronous-file-uploading-using-express-and
With this I can upload files - they appear in my upload folder.
Now I want to achieve, that the upload is linked to the project the user made. E.g.: Jon Doe is logged in, he uploads a picture. Now I want to render his profile page. I query my project model for Jon Doe --> now I want to media files uploaded by him.
So how do I post my media, to the projectSchema of Jon Doe? Afterwards, whats the best way to display all the media in Angular?
------Edit------
I´ve been trying aroud with the extension multer, and I nearly managed to make GET and POST of uploads working. Problem is, I cant fetch any data from the database. My Console gives me a GET /uploads/media/[object%20Object] 304.
The target is: Writing the project_id, with the files to the mediaSchema. So when I´m opening a project, I get all media matching the project_id of this Project. I updated my code for you:
HTML Form
<form id="uploadForm"
enctype="multipart/form-data"
action="/uploads/"
method="post">
<label for="project_id">Ihre Projekt ID</label>
<input type="text" name="project_id" value="{{projects._id}}" readonly>
<input type="file" name="userPhoto"/>
<button type="submit">Hochladen</button>
</form>
<hr>
<img ng-src="{{media.img}}"/>
Angular Controller
var app = angular.module('myApp', []);
var projectId =
app.controller('projectCtrl', function($scope, $http) {
$scope.myVar = false;
$scope.toggle = function() {
$scope.myVar = !$scope.myVar
};
$http.get('/profile/project/').then(function (res){
$scope.projects = res.data;
var projectId = $scope.projects._id;
});
//GET Media
$http.get('/uploads/media/'+projectId).then(function(data){
console.log('Medien-Daten erhalten');
$scope.media = data;
});
});
Routing:
//FILE HANDLING FOR PROJECTMEDIA
var Media = require('./models/media.js');
//GET all the media
app.get('/uploads/', function(req, res, next){
Media.find(function (err, media){
if (err) return next (err);
res.json(media);
});
});
//GET one item
app.get('/uploads/media/:projectId', function(req, res, next){
Media.findOne(req.params , function (err, media){
if (err) return next (err);
res.json(media);
});
});
mediaSchema
var mongoose = require ('mongoose');
var mediaSchema = mongoose.Schema({
img : {data: Buffer, contentType: String},
project_id : String,
updated_at : {type: Date, default: Date.now }
});
projectSchema
var projectSchema = mongoose.Schema({
author : String,
name : String,
description : String,
tags : String,
updated_at : {type: Date, default: Date.now },
active : {type: Boolean, default: false}
});
To answer your questions.
how do I post my media, to the projectSchema of Jon Doe?
In Angular you want to use the $http service. It's very simple, an example for you would be.
HTML
<input id="filebutton" name="filebutton" file-model="myFile" class="input-file" type="file">
<br>
<button ng-click="postForm()" id="singlebutton" name="singlebutton" class="btn btn-primary">Upload</button>
APP
var app = angular.module('jsbin', []);
//we need to use this directive to update the scope when the input file element is changed.
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[0].files[0]);
});
});
}
};
}]);
//use a service to handle the FormData upload.
app.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('userPhoto', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
//all done!
})
.error(function(){
});
};
}]);
app.controller('DemoCtrl', function($scope, $http, fileUpload) {
$scope.postForm = function(){
console.log($scope.myFile);
// Run our multiparty function.
fileUpload.uploadFileToUrl($scope.myFile, '/upload/');
};
});
Afterwards, whats the best way to display all the media in Angular?
Assuming you have your endpoint working correctly. You can do a $http only this time do a get.
JS
// make the request
$http.get('/your/media').then(function(response){
//add to scope
$scope.myMedia = response.data;
});
HTML
<div ng-repeat="photo in myMedia">{{photo}}</div>

angularjs share data config between controllers

I'm wondering what could be a good way to share directive
between controller.
I've got ie two directives to use in different controller
with different configuration the first think I thought of
using like:
//html
<body data-ng-controller="MainCtrl">
<div class="container">
<div data-ui-view></div>
</div>
</body>
//js
.controller('MainCtrl', function ($scope,$upload) {
/*File upload config*/
$scope.onFileSelect = function($files) {
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
$scope.upload = $upload.upload({
url: 'server/upload/url',
method: 'POST',
data: {myObj: $scope.myModelObj},
file: file,
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
console.log(data);
});
}
};
/* Datepicker config */
$scope.showWeeks = true;
$scope.minDate = new Date();
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.dateOptions = {
'year-format': "'yy'",
'starting-day': 1
};
$scope.format = 'MMM d, yyyy';
})
.controller('IndexCtrl', function ($scope) {
})
doing so I can use all the functions in my children controller
but I don't like very much because of collision problems.
Since you cannot use a service (you can't use $scope in a service) the other alternatives could be make an other directive or put the code in a run block
but it's quite the same using a parent controller so
what do you think about ?
UPDATE
what do you think about this approach ?
//outside of angular stauff
function MyTest(){
this.testScope = function(){
console.log('It works');
}
}
//inside a controller
$scope.ns = new MyTest();
//in the view
<p ng-click="ns.testScope()">ppp</p>
RIUPDATE
this seems the best option :)
MyTest.call($scope);
Consider the method described by this post: Extending AngularJS Controllers Using the Mixin Pattern
Instead of copying your methods out of a service, create a base controller that contains those methods, and then call extend on your derived controllers to mix them in. The example from the post:
function AnimalController($scope, vocalization, color, runSpeed) {
var _this = this;
// Mixin instance properties.
this.vocalization = vocalization;
this.runSpeed = runSpeed;
// Mixin instance methods.
this.vocalize = function () {
console.log(this.vocalization);
};
// Mixin scope properties.
$scope.color = color;
// Mixin scope methods.
$scope.run = function(){
console.log("run speed: " + _this.runSpeed );
};
}
Now we can mixin AnimalController into DogController:
function DogController($scope) {
var _this = this;
// Mixin Animal functionality into Dog.
angular.extend(this, new AnimalController($scope, 'BARK BARK!', 'solid black', '35mph'));
$scope.bark = function () {
_this.vocalize(); // inherited from mixin.
}
}
And then use DogController in our template:
<section ng-controller="DogController">
<p>Dog</p>
<!-- Scope property mixin, displays: 'color: solid black' -->
<p ng-bind-template="color: {{ color }}"></p>
<!-- Calls an instance method mixin, outputs: 'BARK BARK!' -->
<button class="btn" ng-click="bark()">Bark Dog</button>
<!-- Scope method mixin, outputs: 'run speed: 35mph' -->
<button class="btn" ng-click="run()">Run Dog</button>
</section>
The controllers in this example are all in the global space and are included in the markup as follows.
<script type="text/javascript" src="lib/jquery.js"></script>
<script type="text/javascript" src="lib/angular.js"></script>
<script type="text/javascript" src="app/controllers/animal-controller.js"></script>
<script type="text/javascript" src="app/controllers/dog-controller.js"></script>
<script type="text/javascript" src="app/controllers/cat-controller.js"></script>
<script type="text/javascript" src="app/app.js"></script>
I haven't tested it, but I don't see why the following wouldn't work:
var myApp = angular.module('myApp', [])
.controller('AnimalController', ['$scope', 'vocalization', 'color', 'runSpeed', function ($scope, vocalization, color, runSpeed) { /* controller code here */}]);
.controller('DogController', ['$scope', '$controller', function($scope, $controller) {
var _this = this;
// Mixin Animal functionality into Dog.
angular.extend(this, $controller('AnimalController', {
$scope: scope,
vocalization: 'BARK BARK!',
color: 'solid black',
runSpeed:'35mph'
}));
$scope.bark = function () {
_this.vocalize(); // inherited from mixin.
}
}]);
see: docs for $controller service
What you want is terrible.
You wouldn't want your controllers to know anything about each other, let alone, one having access to the function of the other. You can just use a Service to achieve that. As for using directives, not sure what exactly you want to happen.
As for your second thing, you can as easily do this
.service('MyTestService', function(){
return {
testScope: function(){
console.log('It works');
}
};
})
.controller('MyController', ['$scope', 'MyTestService', function($scope, MyTestService){
$scope.testScope = MyTestService.testScope;
}])
and in your view:
<p ng-click="testScope()">ppp</p>
I ended up with:
//service
.service('PostUploader',function($upload){
var that = this;
var fileReaderSupported = window.FileReader !== null;
this.notify = null;
this.success = null;
this.showAlert = false;
this.avatar = '';
this.onFileSelect = function($files) {
var $file = $files[0];
var filename = $file.name;
this.avatar = filename;
var isImage = /\.(jpeg|jpg|gif|png)$/i.test(filename);
if(!isImage){
this.showAlert = true;
return;
}
this.showAlert = false;
if (fileReaderSupported && $file.type.indexOf('image') > -1) {
var fileReader = new FileReader();
fileReader.readAsDataURL($file);
fileReader.onload = that.notify;
}
$upload.upload({
url :'/api/post/upload',
method: 'POST',
headers: {'x-ng-file-upload': 'nodeblog'},
data :null,
file: $file,
fileFormDataName: 'avatar'
})
.success(that.success)
.progress(function(evt) {
})
.error(function(data, status, headers, config) {
throw new Error('Upload error status: '+status);
})
};
this.closeAlert = function() {
this.showAlert = false;
};
})
//controller
/* Uploader post */
$scope.dataUrl = null;
$scope.avatar = PostUploader.avatar;
$scope.showAlert = PostUploader.showAlert;
$scope.onFileSelect = PostUploader.onFileSelect;
$scope.closeAlert = PostUploader.closeAlert;
PostUploader.notify = function(e){
$timeout(function() {
$scope.dataUrl = e.target.result;
});
};
PostUploader.success = function(data, status, headers, config) {
$timeout(function() {
$scope.post.avatar = data.url;
});
}
$scope.$watch('avatar',function(newVal, oldVal){
if(newVal) {
$scope.avatar = newVal;
}
});
$scope.$watch('showAlert',function(newVal, oldVal){
$scope.showAlert = newVal;
$scope.dataUrl = null;
});
I did so because I've to do the same thing in create post and edit post but all in all
I've got quite the same repeated code ! :)
The only good thing is the code has got less logic.
obvious but brilliant solution (may be)
(function(window, angular, undefined) {
'use strict';
angular.module('ctrl.parent', [])
.run(function ($rootScope) {
$rootScope.test = 'My test'
$rootScope.myTest = function(){
alert('It works');
}
});
})(window, angular);
angular.module('app',['ctrl.parent'])
.controller('ChildCtrl', function($scope){
});
It's easy and clean and don't see any drawback(it's not global)
UPDATE
'use strict';
(function(window, angular, undefined) {
'use strict';
angular.module('ctrl.parent', [])
.controller('ParentController',function (scope) {
scope.vocalization = '';
scope.vocalize = function () {
console.log(scope.vocalization);
};
});
})(window, angular);
angular.module('app',['ctrl.parent'])
.controller('ChildCtrl', function($scope,$controller){
angular.extend($scope, new $controller('ParentController', {scope:$scope}));
$scope.vocalization = 'CIP CIP';
});
just a little neater and it works CIP CIP :)

Resources