I am new to angular js. I am trying to build a functionality to upload an excel sheet from angular UI and pass its data to an REST API to process it further.
Please find below my code
Dashboard.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html ng-app="msaApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="../js/angular.js"></script>
<script type="text/javascript" src="../js/script.js"></script>
<title>Dashboard</title>
</head>
<body background="../images/bckgd.jpg" >
<div class="header">
<table style="width: 100%; height: 10%; "><tr style="height: 142px; ">
<td align="left" style="width: 20%; "><img src="../images/infosys-bte-logo-GIF.gif" style="width: 280px; height: 54px"></td>
<td align="center" style="width: 80%; "><h1>MSA Complaince monitoring portal</h1></td>
</tr></table>
</div>
{{2+2}}
<div ng-controller="fileController">
<table align="center">
<tr><td>Please choose a file</td></tr>
<tr><td><input type="file" name="uploadFile" file-input="files"></td><td><button ng-click="fileChanged()">Upload me </button></td></tr>
</table>
</div>
</body>
</html>
Script.js
var msaApp1 = angular.module("msaApp",[]);
msaApp1.directive('fileInput',['$parse',function($parse)
{
return{
restrict:'A',
link:function(scope,elm,attrs)
{
alert(elm);
elm.bind('change',function()
{
$parse(attrs.fileInput)
.assign(scope,elm[0].files)
scope.$apply()
})
}
}
}]).controller('fileController' , ['$scope','$http', function($scope,$http)
{
$scope.fileChanged=function(elm)
{
alert(elm);
$scope.files=elm.files
$scope.apply();
alert($scope.files);
}
}])
I am trying to get file object in alert but its giving me below error.
TypeError: Cannot read property 'files' of undefined
at ChildScope.$scope.fileChanged (script.js:25)
at fn (eval at compile (angular.js:15156), <anonymous>:4:153)
at callback (angular.js:26744)
at ChildScope.$eval (angular.js:17972)
at ChildScope.$apply (angular.js:18072)
at HTMLButtonElement.<anonymous> (angular.js:26749)
at defaultHandlerWrapper (angular.js:3613)
at HTMLButtonElement.eventHandler (angular.js:3601)
I don't know JSP so I can put a code in simple angular with HTML. It may helpful to resolve your issue. I can try to guide you to resolve an issue. Please review this may helpful to you.
HTML
<html ng-app="fUploadApp">
<head><title>File upload</title></head>
<body>
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">Upload File</button>
</div>
<script src="angular.min.js"></script>
<script src="app.js"></script>
</body>
</html>
App.js
var fUploadApp = angular.module('fUploadApp', []);
fUploadApp.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]);
});
});
}
};
}]);
fUploadApp.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(){
});
}
}]);
fUploadApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
var uploadUrl = "/savedata";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
Related
I want to bind some dynamic content, loaded by jQuery, to Angular but i couldn't get it work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
<script type="text/javascript">
var module = angular.module('ctrl', []);
module.directive('helpMe', function() {
return {
restrict: 'E',
template: '<div><button ng-click="clicker()">Click 1</button><button ng-click="create()">Create</button><div ng-hide="true">FooBar</div></div>',
controller: ['$scope', function($scope) {
$scope.clicker = function () {
console.log('Clicked...');
};
$scope.create = function () {
$('#foo').contents().clone().appendTo('#bar');
}
}]
}
});
</script>
</head>
<body ng-app="ctrl">
<div id="foo">
<help-me></help-me>
</div>
<div id="bar">
</div>
</body>
If i click the "Click 1" button, the console logs it. If i click the "create" button, a new set of buttons appears. But the new buttons don't work. I could not find out how to get this work. Any ideas?
You need to call $compile on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.
$scope.create = function() {
var clone = $('#foo').contents().clone();
$compile(clone)($scope);
$('#bar').append(clone);
}
check this plnkr
Try this it will work:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
<script type="text/javascript">
var module = angular.module('ctrl', []);
module.directive('helpMe', function() {
return {
restrict: 'E',
template: '<div><button ng-click="clicker()">Click 1</button><button ng-click="create()">Create</button><div ng-hide="true">FooBar</div></div>',
controller: ['$scope','$compile' function($scope,$compile) {
$scope.clicker = function () {
console.log('Clicked...');
};
$scope.create = function () {
$('#foo').contents().clone().appendTo('#bar');
$compile($('#bar'))($scope);
}
}]
}
});
</script>
</head>
<body ng-app="ctrl">
<div id="foo">
<help-me></help-me>
</div>
<div id="bar">
</div>
</body>
I am trying to redirect to another page using angular redirect. But I am getting a couldn't resolve from state error. I followed the How to pass parameter when I redirect the page in angularjs using ui router? link.
Please find below my route.js code:
var helloWorldApp = angular.module('helloWorldApp', ['ui.router']);
helloWorldApp.config(function($stateProvider,$urlRouterProvider) {
$stateProvider
.state('first', {
url: '/first',
templateUrl: 'first.html'
})
.state('second', {
url: '/second',
templateUrl: 'second.html'
});
});
My first.html code
<html lang="en" ng-app="helloWorldApp">
<head>
<meta charset="UTF-8">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-animate.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.14.2.js"></script>
<script type="text/javascript" src="./app/routes.js"></script>
</head>
<script type="text/javascript">
var helloAppConf = angular.module('helloWorldApp', ['ui.router']);
helloAppConf.controller('firstCtrl',function($scope,$state){
$scope.userInput='Hello world from first page';
$scope.getNewPage=function() {
$state.go("second", { id: $scope.userInput });
}
});
</script>
<body>
<div ng-controller="firstCtrl">
<h4>{{userInput}}</h4>
<button ng-click="getNewPage()">New Page</button>
</div>
</body>
</html>
My second.html code
<!DOCTYPE html>
<html lang="en" ng-app="helloWorldApp">
<head>
<meta charset="UTF-8">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-animate.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.14.2.js"></script>
<script type="text/javascript" src="./app/routes.js"></script>
</head>
<script type="text/javascript">
var helloAppConf = angular.module('helloWorldApp', ['ui.router']);
helloAppConf.controller('secondCtrl' , function($scope, $state){
$scope.id = $stateParams.id;
});
</script>
<body>
<div ng-controller="secondCtrl">
<h4>{{id}}</h4>
<button ng-click="getNewPage()">New Page</button>
</div>
</body>
</html>
I am using springboot and my project structure snapshot is attached here:
I am able to access both first.html and second.html pages on my browser. But when I click on the New Page button on first.html, I get the
Error: Could not resolve 'second' from state ''
at Object.t.transitionTo (http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js:7:8834)
at Object.t.go (http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js:7:8182)
at Scope.$scope.getNewPage (http://localhost:8080/first.html:18:16)
at fn (eval at (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js:13322:15), :4:221)
at callback (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js:23549:17)
at Scope.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js:15989:28)
at Scope.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js:16089:25)
at HTMLButtonElement. (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js:23554:23)
at HTMLButtonElement.eventHandler (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js:3298:21)
Please help. Thanks in advance.
In your second html code you inject $state wrongly instead of $stateParams. So that your code didn't work
Inject with $stateParams
var helloAppConf = angular.module('helloWorldApp', ['ui.router']);
helloAppConf.controller('secondCtrl' , function($scope, $stateParams){
$scope.id = $stateParams.id;
});
or use $state.params.id
var helloAppConf = angular.module('helloWorldApp', ['ui.router']);
helloAppConf.controller('secondCtrl' , function($scope, $state){
$scope.id = $state.params.id;
});
I'm trying to get this done using the RUG (Random User Generator) API but I can't get this to work. I should be calling the http request after a click event but it doesn't seems to work. Here is what I've done (and sorry for my amateur code):
index.html
<!DOCTYPE html>
<html lang="en" ng-app>
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div id="clk" style="background-color: indigo; widht: 100px; height: 100px"></div>
{{"Hello world"}}
<div ng-controller="firstController">
{{ store.email}}
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
app.js
var app = angular.module('people', []);
app.controller('firsController', ["http",function (http) {
var store = this;
store.products = [];
$http.get('http://api.randomuser.me').success(function(data){
store.products = data.results[0].user;
})
}]);
OR
var boton = document.getElementById('clk');
boton.addEventListener('click', function () {
$.ajax({
url: 'http://api.randomuser.me/',
dataType: 'json',
success: function(data){
console.log(data.results[0].user);
}
});
});
Neither of this can work. Could I get this to work, to click a button and loading a new user from the api and use it with angular?
This is the correct way to use $http service and scope variables.
<html ng-app="people">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('people', []);
app.controller('firstController', ["$scope", "$http", function ($scope, $http) {
$scope.store = {};
$scope.store.products = [];
$http.get('http://api.randomuser.me').success(function(data){
$scope.user = data.results[0].user;
})
}]);
</script>
</head>
<body>
<div id="clk" style="background-color: indigo; widht: 100px; height: 100px"></div>
<div ng-controller="firstController">
{{ user.email}}
</div>
</body>
</html>
Im buildning a login system with angularjs and php, and after successfully logged in, a new page should be visible to the user.
The problem I have is that the view Im trying to load seems not to be loaded. The page content is not displayed.
Here is my controller:
var gameApp = angular.module("gameApp", []);
gameApp.service('link', function() {
this.user = false;
});
gameApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'partials/firstpage.html',
controller : 'firstPageCtrl'
})
.when('/game', {
templateUrl : 'partials/game.html',
controller : 'gameCtrl'
});
});
gameApp.controller("firstPageCtrl", function($scope,$http,link,$location) {
$scope.doLogin = function() {
$http.post("lib/action.php", {username: $scope.username, password: $scope.password}).success(function(data) {
if(data) {
link.user = data;
console.log(link.user);
$location.path("/game.html");
}
}).error(function(data) {
console.log(data);
});
};
});
gameApp.controller("gameCtrl", function($scope,$http,link,$location) {
alert("hej");
$scope.fisk = "fisk";
/*if(link.user) {
$scope.message = "fisk";
console.log(link.user);
} else {
$scope.message = "Ledsen fisk";
console.log("Är inte satt");
}*/
});
The view that should be loaded is game.html.
Here is my content of game.html:
asdasdsaaaaaaaaaaaaaaaa
<div ng-controller="gameCtrl">
<div id="test" style="border: 1px solid #000; width: 300px; height: 300px;">
{{message}}
{{fisk}}
</div>
</div>
The content above is not displayed.
Here is my index.html
<!DOCTYPE html>
<html ng-app="gameApp">
<head>
<link href="css/style.css" rel="stylesheet" type="text/css">
<meta content="text/html;charset=UTF-8" http-equiv="content-type" />
</head>
<body ng-controller="firstPageCtrl">
<div id="layout">
<div id="topcontent">
</div>
<div id="middlecontent">
<div ng-view></div>
</div>
<div id="bottomcontent">
{{"AngularJS"}}
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="js/mastercontroller.js"></script>
</html>
Try changing $location.path("/game.html"); to $location.path("/game"); in firstPageCtrl so it matches the exact declaration in your gameApp.config.
I have created an app that uses Google Maps, the map showed up before I did my routing. But after routing it wont display. Here is my code for the app.
JS:
search-controller.js
(function() {
searchController.$inject = ['$scope'];
function searchController($scope) {
$scope.ASiteLocs = [There Is Code In here that is too long and irrelevant to the map];
$scope.SSiteLocs = [""];
$scope.SiteLocs = $scope.SSiteLocs.concat($scope.ASiteLocs);
angular.forEach($scope.SiteLocs, function(location) {
var clength = location.Point.coordinates.length;
if (location.Point.coordinates.substring(clength - 2, clength) === ",0") {
location.Point.coordinates = location.Point.coordinates.substring(0, clength - 2).split(",");
Lat = location.Point.coordinates[0];
Lon = location.Point.coordinates[1];
Com = ",";
location.Point.coordinates = Lon.concat(Com, Lat);
}
angular.forEach($scope.SSiteLocs, function(object) {
object.carrier = 'Sprint';
});
angular.forEach($scope.ASiteLocs, function(object) {
object.carrier = 'AT&T';
});
});
}
angular.module("siteLookUpApplication").controller('searchController', searchController);
}());
map-controller.js
(function() {
mapController.$inject = ['$scope', '$routeParams'];
function mapController($scope, $routeParams) {
function initialize() {
var mapOptions = {
center: site.Point.coordinates,
zoom: 5
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
// Save the locationName in the url to the scope
$scope.locationName = $routeParams.locationName;
}
angular.module("siteLookUpApplication").controller("mapController", mapController);
}());
app.js
(function() {
angular.module("siteLookUpApplication", ["ngRoute"]);
angular.module("siteLookUpApplication").config(function($routeProvider) {
$routeProvider
.when("/search", {
templateUrl: "search.html",
controller: "searchController"
})
.when("/map/:locationName", {
templateUrl: "map.html",
controller: "mapController"
})
.otherwise({
redirectTo: '/search'
});
});
}());
HTML:
map.html
<style>
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100%
background:#fff;}
</style>
<div>
<div><a ng-href="#/search">Back To Search</a></div>
<p>Map for {{locationName}}</p>
<div id="map-canvs"></div>
</div>
index.html
<!DOCTYPE html>
<html ng-app="siteLookUpApplication">
<head>
<link href='http://fonts.googleapis.com/css?family=Droid+Serif' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="style.css" type='text/css'/>
<script data-require="angular.js#*" data-semver="1.2.17" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.js"></script>
<script data-require="jquery#*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script data-require="google-maps#1.0.0" data-semver="1.0.0" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script data-require="angular-route#*" data-semver="1.2.17" src="http://code.angularjs.org/1.2.17/angular-route.js"></script>
<script src="app.js"></script>
<script src="map-controller.js"></script>
<script src="search-controller.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC0wdLb9-Os4YVxn_JR2sY08xEN-1aJkMM"></script>
<title>Site ID</title>
</head>
<body link="white" vlink="white">
<div class="text-center">
<h1>Site Finder</h1>
<div id="map-canvas"></div>
<div ng-view></div>
</div>
</body>
</html>
search.html
<div>
<input type="text" ng-model="search" border="1" placeholder="Please enter site name..." />
<table border="1" width="100%">
<thead>
<tr>
<td>Name</td>
<td>Carrier</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="site in SiteLocs | filter : search">
<td>
<a ng-href="#/map/{{site.name}}">
{{site.name}}
</a>
</td>
<td>
{{site.carrier}}
</td>
</tr>
</tbody>
</table>
</div>
Here is a plunk with my project if that is easier: http://plnkr.co/edit/AiVc6nccqke8Jluonpxl?p=info
You have a few problems:
The Google Maps api is loaded twice
Google Maps should be loaded before Angular
jQuery should be loaded before Angular
In the map.html the div id has a typo
In the maps controller "site" is unresolved (for the center property)
map-canvas exists in the index.html (this should be removed)
In the map controller the initialize function is declared but never called
The CSS on the actual map element is a little wonky and will not display -- for testing put a static height on it or something
App Structure notes:
When using document and window you should instead inject $document and $window
Perhaps you can use a directive for the map instead of a controller -- see http://angular-google-maps.org/
The filtered list looks pretty long consider using ReactJS or pagination.
executiveLiveTracking(executive) {
debugger
let isOpenLiveTracking = executive !== undefined ? PreventMapRendering(executive.deliveryExecutiveId, true) : false;
if (isOpenLiveTracking) {
this.setState({
isLengthExceededMap: false,
DeliveryExecutiveId: executive.deliveryExecutiveId,
liveTrackingModalVisible: true,
snapPointList: [],
liveTrackingExecutiveName: executive.executiveName,
liveTrackingExecutiveLat: executive.executiveLatitude,
liveTrackingExecutiveLng: executive.executiveLongitude
});
}
else {
MessageBox(Constants.ERROR_MSG_FOR_MAP_RENDERING, Constants.INFO);
}