Angular.js: Error: Module 'MyApp' is not available - javascript

I would like to use this plunk locally on my machine. However, when I either run it with the local Python server or http-server, I keep getting the following Error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
My html file looks like this:
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="utf-8" />
<title>Custom Plunker</title>
<script scr="main.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.1/papaparse.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-file-upload/1.1.5/angular-file-upload.min.js"></script>
<link rel="stylesheet" href="main.css">
</head>
<body ng-controller="MyCtrl">
<h1>CSV</h1>
<div>
<input type="checkbox" ng-model="append">
Append to existing on drag & drop
</div>
<div class="drop-container" nv-file-drop nv-file-over uploader="uploader">
<textarea ng-model="csv" placeholder="Enter your CSV here, or drag/drop a CSV file"></textarea>
</div>
<h1>D3 Flare JSON</h1>
<div>
<input type="checkbox" ng-model="compact"> Compact
</div>
<div>
<input type="text" ng-model="tags.parent" placeholder="parent tag">
<input type="text" ng-model="tags.children" placeholder="children tag">
<input type="text" ng-model="tags.leaf" placeholder="leaf tag">
<input type="text" ng-model="tags.size" placeholder="size tag">
</div>
<textarea readonly ng-model="json"></textarea>
</body>
</html>
And the main.js file looks like this:
CSV to D3 Flare JSON converter in AngularJSPreview Edit Code
index.html
main.js
main.css
main.js
angular.module('myApp', ['angularFileUpload'])
.factory('FlareJson', ['$q', function($q) {
function updateTree(curr, arr, tags) {
if ((arr.length || 0) < 2) {
return;
}
if (!curr.hasOwnProperty(tags.children)) {
curr[tags.children] = [];
}
var elem;
if (arr.length == 2) {
elem = {};
elem[tags.leaf] = arr[0];
elem[tags.size] = arr[1];
curr[tags.children].push(elem);
} else {
curr[tags.children].some(function(e) {
if (e[tags.parent] == arr[0] || e[tags.leaf] == arr[0]) {
elem = e;
return true;
}
});
if (!elem) {
elem = {};
elem[tags.parent] = arr[0];
curr[tags.children].push(elem);
}
updateTree(elem, arr.slice(1), tags);
}
}
function buildJson(csv, compact, tags) {
var deferred = $q.defer();
var result = {};
result[tags.parent] = 'flare';
Papa.parse(csv, {
header: false,
dynamicTyping: true,
complete: function(csvArray) {
csvArray.data.forEach(function(line) {
if (line.length) {
updateTree(result, line, tags);
}
});
if (compact) {
deferred.resolve(JSON.stringify(result));
} else {
deferred.resolve(JSON.stringify(result, null, 2));
}
}
});
return deferred.promise;
}
return buildJson;
}])
.controller('MyCtrl', ['$scope', 'FileUploader', 'FlareJson',
function($scope, FileUploader, FlareJson) {
$scope.csv = "";
$scope.compact = false;
$scope.json = "";
$scope.tags = {
parent: 'skill',
children: 'children',
leaf: 'name',
size: 'level'
};
$scope.uploader = new FileUploader();
$scope.uploader.onAfterAddingFile = function(fileItem) {
var reader = new FileReader();
reader.onloadend = function(event) {
$scope.$apply(function() {
if ($scope.append) {
$scope.csv += event.target.result;
} else {
$scope.csv = event.target.result;
}
});
};
reader.readAsText(fileItem._file);
};
function update() {
FlareJson($scope.csv, $scope.compact, $scope.tags).then(function(json) {
$scope.json = json;
});
}
$scope.$watchGroup(['csv', 'compact'], update);
$scope.$watchCollection('tags', update);
}]);
I don't understand what I'm doing wrong. I already searched for similar error messages, but nothing that I found could help me to solve my problem.

You load your script file before angularjs file that's why you are getting this error.
So, Add your "main.js" file after "angular.js" file.
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js"></script>
<script scr="main.js"></script>

I believe it's because you're loading your main.js before you load Angular. Try putting your script at the end of the script definitions:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.1/papaparse.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-file-upload/1.1.5/angular-file-upload.min.js"></script>
<script scr="main.js"></script>

Oh, solved! Turns out, that the following couple of first lines in main.js were causing the trouble:
CSV to D3 Flare JSON converter in AngularJSPreview Edit Code
index.html
main.js
main.css
main.js
I removed them from main.js, now it works - yuhuu! :)

Related

Pluralsight - AngularJS: Get Started

I follow the "AngularJS: Get Started" course from Plualsight, and I reach the Routing module, so I have some files in Plunker, on the course they can see on Preview page the title which is "Github Viewer" and a search bar. But I still get errors in console, and I do not know why, my code should be identical as their code.
So I have the following files :
app.js
(function() {
var app = angular.module('githubViewer', ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/main", {
templateUrl: "main.html",
controller: "MainController"
})
.otherwise({redirectTo: "/main"});
});
}());
github.js
(function() {
var github = function($http) {
var getUser = function(username) {
return $http.get("https://api.github.com/users/" + username)
.then(function(response) {
return response.data;
});
};
var getRepo = function(user) {
return $http.get(user.repos_url)
.then(function(response) {
return response.data;
});
};
return {
getUser : getUser,
getRepo : getRepo
};
};
var module = angular.module("githubViewer");
module.factory("github", github);
}());
index.html
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<script data-require="angular.js#*" data-semver="1.3.14" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script data-require="angular-route#*" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script scr="app.js"></script>
<script src="MainController.js"></script>
<script src="github.js"></script>
</head>
<body>
<h1>Github Viewer</h1>
<div ng-view></div>
</body>
</html>
main.html
<div>
{{ countdown }}
<form name="searchUser" ng-submit="search(username)">
<input type="search" required="" ng-model="username" />
<input type="submit" value="Search" />
</form>
</div>
MainController.js
// Code goes here
(function() {
var app = angular.module("githubViewer");
var MainController = function($scope, $interval, $location) {
console.log("Atentie!")
var decrementCountdown = function() {
$scope.countdown -= 1;
if ($scope.countdown < 1) {
$scope.search($scope.username);
}
};
var countdownInterval = null;
var startCountdown = function() {
countdownInterval = $interval(decrementCountdown, 1000, $scope.countdown);
};
$scope.search = function(username) {
if (countdownInterval) {
$interval.cancel(countdownInterval);
$scope.countdown = null;
}
//
};
$scope.username = "Angular";
$scope.countdown = 5;
startCountdown();
};
app.controller("MainController", MainController);
}());
userdetails.html
<div id="userDetails">
<h2>{{user.name}}</h2>
<img ng-src="{{user.avatar_url}}" title="{{user.name}}">
<div>
Order:
</div>
<select ng-model="repoSortOrder">
<option value="+name">Name</option>
<option value="-stargazers_count">Stars</option>
<option value="+language">Language</option>
</select>
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Stars</th>
<th>Language</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="repo in repos | limitTo:10 | orderBy:repoSortOrder">
<td>{{repo.name}}</td>
<td>{{repo.stargazers_count | number }}</td>
<td>{{repo.language}}</td>
</tr>
</tbody>
</table>
And the style.css which is empty.
So at this point I should see in a separete window something like in the following picture and no errors in console.
But I se only the title, like in the following picture
and errors
Could someone help me to understand why isnt' work ?
Was some changes in AngularJS and the course isn't up to date ?
You made a typo
<script scr="app.js"></script>
should be
<script src="app.js"></script>
Also make sure that when using angularjs core api's, all the API should be off same version. Here you're using angularjs (ver. 1.3.12) & angular-route (ver. 1.6.2)
Change both to 1.6.2 or latest
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular-route.js"></script>
Demo Here

How to send an angular param to an onclick event?

here we go...
I have a controller
$scope.selectedScript = {};
$scope.selectedScript.scriptId = null;
$scope.selectScript = function(script, index) {
$scope.selectedScript = script;
$scope.selectedRow = index;
myAppFactory.updateTextArea(script).success(
function(data) {
$scope.selectedScript = data;
});
};
$scope.getSelectedClass = function(script) {
if ($scope.selectedScript.scriptId != undefined) {
if ($scope.selectedScript.scriptId == script.scriptId) {
return "selected";
}
}
return "";
};
i have a html page
<label>Script ID:</label>
<input name="scriptId"
type="text"
id="scriptId"
ng-model="selectedScript.scriptId"
ng-disabled="true"
value="{{selectedScript.scriptId}}" />
and now thx to IARKI i have this
<script type="text/javascript">
function goTo (){
var param1 = angular.element(document.querySelector('.scriptId')).scope.selectedScript.scriptId;
location.href=this.href + '?scriptId='+param1;
return false;
}
</script>
Debug
I have also a list of scripts in a table
<table class="scripts" name="tableScript" arrow-selector>
<tr bgcolor="lightgrey">
<th>Script ID</th>
<th>File Name</th>
</tr>
<tr
ng-repeat="s in scripts | filter:searchField | orderBy:'scriptId'"
ng-click="selectScript(s, $index)" ng-class="getSelectedClass(s)">
<td>{{s.scriptId }}</td>
<td>{{s.fileName }}</td>
</tr>
</table>
Then i press the link above, and a new tab appears, but the link is still the
http://localhost:8080/DSS-war/debug.html
but i need it to open in a new tab as well as to be like this:
http://localhost:8080/DSS-war/debug.html?scriptId=1
http://localhost:8080/DSS-war/debug.html?scriptId=2
http://localhost:8080/DSS-war/debug.html?scriptId=12
and so on...with numbers
any idea?
And it has to be the onclick function, not the ng-click
I know how it works on ng-click, but i need to make it work on onclick...
and now i get this from the chrome debugger:
Uncaught TypeError: Cannot read property 'scriptId' of undefined
in the line
var param1 = angular.element(document.querySelector('.scriptId')).scope.selectedScript.scriptId;
You can try to access angular scope using pure javascript
<script type="text/javascript">
function goTo (){
var param1 = angular.element("#scriptId").scope().selectedScript.scriptId;
location.href=this.href + '?scriptId='+param1;
return false;
}
</script>
Debug
Update
Useless code but I hope it will help you
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>My application</title>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<label>Script ID:</label>
<input name="scriptId" type="text" id="scriptId" ng-model="selectedScript.scriptId" ng-disabled="true">
<button onclick="generateID()">Set code</button>
Debug
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script type="text/javascript">
function generateID() {
var code = Math.floor(Math.random() * 20) + 1;
document.getElementById('scriptId').setAttribute('value', code.toString());
}
function goTo() {
var scope = angular.element(document.querySelector('#scriptId')).scope();
scope.$apply(function () {
scope.selectedScript.scriptId = document.querySelector('#scriptId').getAttribute('value');
});
scope.changeURl();
}
angular.module('myApp', [])
.controller('myCtrl', function ($scope, $window) {
$scope.selectedScript = {};
console.log('We are in controller');
$scope.changeURl = function () {
$window.open('http://localhost:8080/DSS-war/debug.html?scriptId=' + $scope.selectedScript.scriptId, '_blank');
}
});
</script>
</html>

How to get the Local Storage data into the view file Using Angular js

Hello I am beginner in mean Stack. and I have data in localstorage and I want to fetch the data from the local storage and show in html file but I don't know How to get it. on the view file.
$scope.useredit = function (d) {
var user_id = d._id;
var dataToModify;
angular.forEach($scope.dp, function (value, key) {
if (user_id == value._id) {
dataToModify = value;
$localStorage.userData = dataToModify;
console.log($localStorage.userData.name);
$location.path('/useredit');
}
});
}
when I type localStorage; into console it show
ngStorage-userData
:
"{
"_id":"5846692617e0575c0e0c2211",
"password":123456,
"email":"montyy1981#gmail.com",
"name":"digvijay12","__v":0
}"
How to get it value into the view file.I used like
<div>{{userData.email}}</div>
But it is not showing data.please help me how to fetch localstorage data and show into view file.
You can use core concept without ngStorage....
https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
localStorage.setItem("userData", $scope.Data);
$scope.storageData = localStorage.getItem("userData");
<p>{{storageData.email}}</p>
How to get the localStoragedata anywhere this is very simple we have to pass localStorage data into the controller global variable suppose
we have the data into localstorage
$scope.useredit = function (d) {
var user_id = d._id;
var dataToModify;
angular.forEach($scope.dp, function (value, key) {
if (user_id == value._id) {
dataToModify = value;
$localStorage.userData = dataToModify;
console.log($localStorage.userData.name);
$location.path('/useredit');
}
});
}
we have to define pass $localStorage.userData into the other variable after controller start.
app.controller("usercontroller",function($scope,$http, $localStorage,$location){
$scope.registeruser = $localStorage.userData;
$scope.useredit = function (d) {
var user_id = d._id;
var dataToModify;
angular.forEach($scope.dp, function (value, key) {
if (user_id == value._id) {
dataToModify = value;
$localStorage.userData = dataToModify;
console.log($localStorage.userData.name);
$location.path('/useredit');
}
});
}
});
For better understanding click this DEMO
In the controller you need to inject "ngStorage" angular.module('MyApp', ["ngStorage"]).
And add the dependency script link <script src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
HTML
<html ng-app="MyApp">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="MyController">
<input type="button" value = "Save" ng-click = "Save()" />
<input type="button" value = "Get" ng-click = "Get()" />
</div>
</body>
</html>
Script.js
var app = angular.module('MyApp', ["ngStorage"])
app.controller('MyController', function ($scope, $localStorage, $sessionStorage, $window) {
$scope.Save = function () {
$localStorage.email = "xyz#gmail.com";
}
$scope.Get = function () {
$window.alert($localStorage.email);
}
});
Hope it will be usefull for you.

Some problems with Angular JS and Javascript

I'm a newbie in Javascript and Angular JS programming and I'm trying to make a currency converter using Yahoo Finance API, but also I want to input directly the initial value in the script without clicking the button or pressing enter, so i figured that using Angular JS would be great. But it doesn't work properly and I think the problem might be in function calculate($scope). Please, can you help me?
<html ng-app>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
function currencyConverter(currency_from,currency_to,currency_input){
var yql_base_url = "https://query.yahooapis.com/v1/public/yql";
var yql_query = 'select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20("'+currency_from+currency_to+'")';
var yql_query_url = yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
var http_response = httpGet(yql_query_url);
var http_response_json = JSON.parse(http_response);
return http_response_json.query.results.rate.Rate;
}
//The problem starts here?
function calculate($scope)
{
$scope.total= function(){
var currency_from = "USD";
var currency_to = "INR";
var rate = currencyConverter(currency_from,currency_to,$scope.currency_input);
return rate;
};
}
</script>
<script src="js/angular.js"></script>
</head>
<body>
<div ng-controller="calculate">
<div style="float:left;">
<form>
<input type="text" ng-model="currency_input" value="0"/> =
</form>
</div>
<div style="float:left">
{{total()}}
</div>
</div>
<div style="clear: both;"></div>
</body>
</html>
There are a few erros in your code using AngularJS. You forgot to start your application module and add a controller.
I made a few corrections and I tested, it is working:
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
</head>
<body>
<div ng-controller="MyController">
<div style="float:left;">
<form>
<input type="text" ng-model="currency_input" ng-change="total()" value="0"/> =
</form>
</div>
<div style="float:left">
{{ rate }}
</div>
</div>
<div style="clear: both;"></div>
<script>
angular.module('app', [])
.controller('MyController', function($scope, $http) {
function currencyConverter(currency_from,currency_to) {
var yql_base_url = "https://query.yahooapis.com/v1/public/yql";
var yql_query = 'select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20("'+currency_from+currency_to+'")';
var yql_query_url = yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
$http.get(yql_query_url).then(function(response) {
$scope.rate = $scope.currency_input*response.data.query.results.rate.Rate;
});
}
$scope.total = function() {
var currency_from = "USD";
var currency_to = "INR";
currencyConverter(currency_from, currency_to);
};
});
</script>
</body>
</html>
I don't recommend you to use jquery to make http calls. Use $http instead!
One problem, which should be the first to be corrected and go from there, is that you are referencing an angular concept $scope in your scripts before you actually declare the angular library.
To correct this, move your angular library script tag up above your other script tag (but below the jquery script tag.
You should take a look at services (https://docs.angularjs.org/guide/services).
With that you can just create a service and put all of your 'Yahoo' related functions in one place. Then just inject it into your directive/controller.
ex:
.service('yahooRelatedLogicSrvc', function () {
return {
httpGet: function httpGet(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
}
})
.controller('sampleCtrl', function ($scope, yahooRelatedLogicSrvc) {
var url = 'http://yahoo.com';
$scope.httpGet = yahooRelatedLogicStvc.httpGet(url);
}
And you can just put returns of your service functions as $scope properties etc.
I really can see why you should use in line javascript in that scenario.
Angular makes something like this much easier than what you're attempting. There's an $http service for performing a GET, for one, so you can leave out jquery and create something much simpler like ConverterService in my example.
Since your input is bound to a scope variable, you don't need to set value="0", simply set $scope.currency_input to your default value in your controller. I created a convert function on the scope, which will update the output whenever its called. It's called once at the bottom of the controller, but could be bound to a button in your html by simply doing something like this: <button ng-click="convert()">Convert value</button>
var app = angular.module('calc', []);
app.controller('MainCtrl', function($scope, ConverterService) {
// default your currency input
$scope.currency_input = 10;
var currency_from = "USD";
var currency_to = "INR";
$scope.convert = function() {
ConverterService.getConversions(currency_from, currency_to)
.then(function(response) {
// put your logic to convert the value here
var convertedVal = null; // = $scope.currency_input * response.something etc...
$scope.result = convertedVal;
});
};
$scope.convert();// run once when the controller loads to get defaulted input conversion
});
app.factory('ConverterService', function($http) {
return {
getConversions: function(from, to, val) {
var endpoint = ''; // build your endpoint here
return $http.get(endpoint);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="calc">
<div ng-controller="MainCtrl">
<input type="text" ng-model="currency_input">= {{result}}
</div>
</html>

Validating file extension in AngularJs before uploading

I am uploading images for our application to the server.
Is there any way to validate the extensions in client side by JS before submitting them to the server before uploading them to server?
I am using AngularJs to handle my front-end.
You can use this simple javascript to validate. This code should be put inside a directive and on change of file upload control.
var extn = filename.split(".").pop();
Alternatively you can use javascript substring method also:
fileName.substr(fileName.lastIndexOf('.')+1)
You can create a angular directive, something like this should work (Change the accepted values in the validFormats array);
HTML:
<form name='fileForm' >
<input type="file" name="file" ng-model="fileForm.file" validfile>
</form>
Javascript:
angular.module('appname').directive('validfile', function validFile() {
var validFormats = ['jpg', 'gif'];
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
ctrl.$validators.validFile = function() {
elem.on('change', function () {
var value = elem.val(),
ext = value.substring(value.lastIndexOf('.') + 1).toLowerCase();
return validFormats.indexOf(ext) !== -1;
});
};
}
};
});
for file validation i.e required,file extension,size.Create custom directive and used angular js ng-message module for simplify the validation errors
HTML
<input type="file" ng-model="imageFile" name="imageFile" valid-file required>
<div ng-messages="{FORMNAME}.imageFile.$error" ng-if="{FORMNAME}.imageFile.$touched">
<p ng-message="required">This field is required</p>
<p ng-message="extension">Invalid Image</p>
</div>
Angular JS
customApp.directive('validFile', function () {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ngModel) {
var validFormats = ['jpg','jpeg','png'];
elem.bind('change', function () {
validImage(false);
scope.$apply(function () {
ngModel.$render();
});
});
ngModel.$render = function () {
ngModel.$setViewValue(elem.val());
};
function validImage(bool) {
ngModel.$setValidity('extension', bool);
}
ngModel.$parsers.push(function(value) {
var ext = value.substr(value.lastIndexOf('.')+1);
if(ext=='') return;
if(validFormats.indexOf(ext) == -1){
return value;
}
validImage(true);
return value;
});
}
};
});
Require
angular-messages.min.js
Here is the complete code for validating file extension usign AngularJs
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type='text/javascript'>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.setFile = function(element) {
$scope.$apply(function($scope) {
$scope.theFile = element.files[0];
$scope.FileMessage = '';
var filename = $scope.theFile.name;
console.log(filename.length)
var index = filename.lastIndexOf(".");
var strsubstring = filename.substring(index, filename.length);
if (strsubstring == '.pdf' || strsubstring == '.doc' || strsubstring == '.xls' || strsubstring == '.png' || strsubstring == '.jpeg' || strsubstring == '.png' || strsubstring == '.gif')
{
console.log('File Uploaded sucessfully');
}
else {
$scope.theFile = '';
$scope.FileMessage = 'please upload correct File Name, File extension should be .pdf, .doc or .xls';
}
});
};
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
<input type="file"
onchange="angular.element(this).scope().setFile(this)">
{{theFile.name}}
{{FileMessage}}
</div>
</body>
</html>
You can add a custom directive which checks for the element.files array in order to check the type on the onchange event.
There is no embedded validation for file input.
File Upload using AngularJS
There are many modules that can help you with this. Any one of these should allow you to define a filter to only upload certain file extensions.
If you're looking for a simpler solution, you can use something like string.js to ensure the filenames of the files being uploaded are of extension '.png'.

Categories

Resources