I've been trying out AngularJS by creating a simple gallery that gets images from a json file, but somehow I can't seem to display the data.
index.html:
<!DOCTYPE html>
<html ng-app="portfolioApp">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div ng-controller="GalleryController" >
<ul>
<li ng-repeat="image in gallery.galleryData">
<a ng-href="">{{image.IMAGE_WIDTH}}
<img class="thumbnail" ng-src="{{IMAGE_LOCATION+image.image}}" />
</a>
</li>
</ul>
</div>
</body>
</html>
app.js:
var app = angular.module('portfolioApp',[]);
app.controller('GalleryController',['$http', function($http){
var gallery = this;
gallery = [];
gallery.IMAGE_WIDTH = 405;
gallery.IMAGE_LOCATION = "http://rabidgadfly.com/assets/angular/gallery1/";
$http.get("images.json").success(function(data){
gallery.galleryData = data;
});
}]);
I think the issue has something to do with the scope of the gallery variable, but i'm not sure: http://i.stack.imgur.com/VBGku.png
Scopes provide APIs ($apply) to propagate any model changes through
the system into the view from outside of the "Angular realm"
(controllers, services, Angular event handlers).
So you should add gallery to $scope then it can be accessed in the View:
var app = angular.module('portfolioApp',[]);
app.controller('GalleryController',['$http', '$scope', function($http, $scope){
$scope.gallery = [];
$scope.gallery.IMAGE_WIDTH = 405;
$scope.gallery.IMAGE_LOCATION = "http://rabidgadfly.com/assets/angular/gallery1/";
$http.get("images.json").success(function(data){
$scope.gallery.galleryData = data;
});
}]);
Related
I was curious if using input type = "file" will store the actual file that was selected? If so, how would I display that file, preferably a photo, inside of a div or span? I'm working on a project where people can sell their stuff. I'm looking for a way to display the picture that a user submits, somewhat like the way Facebook does.
How would you display that file
You would have a server recieve the form data, and then do one of the following
Serve the posted file from the server itself.
Upload the file to another server or cloud which serves the file.
You can then send this hosted URL to the client as an image source to show it.
You'll want to check the file to make sure it is not mallicious, and probably randomise the name to make attacking the system harder, to prevent someone from uploading a PHP shell and taking over the server.
I have figured out a way using javascript to display the picture after it's been selected for upload. The code is as follows (Entire document).
<!doctype html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/reset.css"> <!-- CSS reset -->
<link rel="stylesheet" href="css/style.css"> <!-- Resource style -->
<script src="js/modernizr.js"></script> <!-- Modernizr -->
<script>
function displayProduct(){
var product = document.getElementById("productTitle").value;
var productDesc = document.getElementById("productDescription").value;
var files = document.getElementById("blah").src;
document.getElementById("showProduct").style.display = "block";
document.getElementById("productHead").innerHTML = product;
document.getElementById("productD").innerHTML = productDesc;
document.getElementById("photo").innerHTML = files;
}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#photo')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
<title>XXXXXXXXX dot Com</title>
</head>
<body>
<header>
<img src = "brownBag.jpg" width = "8%" style = "float: left;">
<h3>Deal Finder dot Com</h3>
<nav class="cd-stretchy-nav">
<a class="cd-nav-trigger" href="#0">
Menu
<span aria-hidden="true"></span>
</a>
<ul>
<li><span>The Homepage of Nephilim42 Coding</span></li>
<li><span>CSS Portfolio Project</span></li>
<li><span>Javascript Portfolio Project</span></li>
<li><span>Play a game of Darts! Powered by Javascript</span></li>
<li><span>My First Business Website</span></li>
</ul>
<span aria-hidden="true" class="stretchy-nav-bg"></span>
</nav>
</header>
<main class="cd-main-content">
<label for = "form">
<form name = "postForm" id = "postForm" method = "POST" action = "">
<p>What are you selling?
<input type = "text" name = "productTitle" id = "productTitle">
</p><br>
<p>Please describe your product.
<textarea name = "productDescription" id = "productDescription" cols = "50" rows = "6"></textarea>
</p><br>
<p>Upload Picture:
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</p>
<input type = "button" name = "post" id = "post" value = "POST" onClick = "displayProduct()"><br>
</form>
<div id = "showProduct">
<p>Product Title:
<span id = "productHead"></span>
</p><br>
<p>Product Description:
<span id = "productD"></span>
</p><br>
<p>Uploaded Photo:
<span id = "photo"></span>
</p>
</div>
<script src="js/jquery-2.1.4.js"></script>
<script src="js/main.js"></script> <!-- Resource jQuery -->
</body>
</html>
Below are some attached images. Unfortunately because I have low reputation here on stackOverflow, only the link will attach. Which do work when copied and pasted into the URL search bar. These images show the steps with what happens when uploading a file. unfortunately I have ran into a problem, but I will work on fixing it. The problem is on image #2. The second chunk of javascript in the readURL function is a failed attempt to rectify that.
Image 1) Upload button clicked, selecting image
Image 2) After image is selected and posted, the value of the file is sent via innerHTML to a span. The value seems to be a super long character string rather than the image in the span. I will try to work on this and fix it, and post on this thread the solution.
1 https://i.stack.imgur.com/2Ev4b.png
2 https://i.stack.imgur.com/L0ymG.png
This question already has answers here:
Angularjs Uncaught Error: [$injector:modulerr] when migrating to V1.3
(5 answers)
Closed 6 years ago.
my controller.js file
function ServicesCtrl($scope) {
console.log("Hello From ServicesCtrl");
$scope.message = "Hello";
}
index.html file
<html>
<head>
<title>The MEAN Stack</title>
<link href="css/bootstrap.css" rel="stylesheet" />
<script src="js/angular.min.js"></script>
<script src="features/services/controller.js"></script>
</head>
<body ng-app="">
<div class="container" ng-controller="ServicesCtrl">
<h1>Service Client Maker</h1>
{{message}}
</div>
</body>
</html>
it is not displaying my message. controller.js file is not accessable
Its clear that you are trying to define a controller like a simple js function.
But, It works in a different way.
You have to initialize an angular app within an java-script variable like this,
var app=angular.module("MyApp");
and handle that entire angular application, through that js variable "app".
I strongly recommend you to completely go through below tutorials.. Then, Start creating the App..
https://www.tutorialspoint.com/angularjs/angularjs_mvc_architecture.htm
http://www.w3schools.com/angular/default.asp
You have to define your angular application and its modules.
var app = angular.module('myApp');
app.controller('serviceController', function() {
$scope.message = "Nice, I now know how to create an angular app";
})
And you will now be able to access it on your page:
<body ng-app="myApp">...
<div ng-controller="serviceController">...
{{message}}
This should help you since you're getting started with angular.
Here this example
define your controller name (controller.js)
var app = angular.module('myApp', []);
app.controller('ServicesCtrl', function($scope) {
$scope.message = "Hello";
});
define your app name (index.html)
<body ng-app="myApp">
<div class="container" ng-controller="ServicesCtrl">
<h1>Service Client Maker</h1>
{{message}}
</div>
</body>
I apologize for the poor formatting. Basically, "clientCount" is appearing as {{clientCount}} on my screen, rather than the integer '10'. Any ideas? Thank you!
var app = angular.module('metaDashboard', []);
/**This is for the meta-dashboard home page
*/
app.controller('TotalNumberController', ['$scope', function($scope) {
$scope.clientCount = '10';
$scope.campaignCount = '20';
$scope.accountCount = '10';
$scope.userCount = '100';
}
]);
--------------------------------------------------------------------
<html lang="en" ng-app="app">
<body class="page-body" data-url="http://neon.dev" ng-app="app">
<div class="row" ng-controller="TotalNumberController">
<div class="icon"><i class="entypo-globe"></i></div>
<div class="num"> {{clientCount}} </div>
<h3>Clients</h3>
<p></p>
</div>
</body>
</html>
Your app is called metaDashboard not app, you should change your code to the following:
<html lang="en" ng-app="metaDashboard">
Also ensure that you have angular.js files included in your head section.
Full snippet:
var app = angular.module('metaDashboard', []);
app.controller('TotalNumberController', ['$scope', function($scope) {
$scope.clientCount = '10';
$scope.campaignCount = '20';
$scope.accountCount = '10';
$scope.userCount = '100';
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.1/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="metaDashboard">
<div ng-controller="TotalNumberController">
<h1>{{clientCount}}</h1>
</div>
</body>
</html>
I have also included this Plunker here for you demonstrating it working:
https://plnkr.co/edit/t80RjCqjmE3y9bOkESo0?p=preview
As an additional note, it may be best to use the ViewModel syntax rather than $scope which I believe is best practice and may help you if you ever nested your AngularJS controllers.
I am making a test app and User registration is going all fine but my Login button won't login because the server responds with 404 on controllers that have the logging in function.
The code for server.js is below:
var mongoose = require('mongoose');
var bodyParser = require ('body-parser');
var express = require('express');
var multiPart = require('connect-multiparty');
var multipartMiddleware = multiPart();
var app =express();
var authenticationController = require('./server/controllers/authenticationController');
var profileController = require('./server/controllers/profileController');
mongoose.connect('mongodb://localhost:27017/timeWaste');
app.use(bodyParser.json());
app.use(multipartMiddleware);
app.use('/app',express.static(__dirname + "/app"));
app.use('/node_modules', express.static(__dirname+"/node_modules"));
//Authentication
app.post ('/users/signup', authenticationController.signup);
app.post('/users/login', authenticationController.login);
//Profile
app.post('/profile/edit', multipartMiddleware, profileController.updatePhoto);
app.post('/profile/updateUsername', profileController.updateUsername);
app.post('/profile/updateBio', profileController.updateBio);
app.get('/', function(req,res) {
res.sendfile('index.html');
});
app.listen(3000, function() {
console.log('Listening');
});
The code for my navigationController where the login function is written is as follows:
(function(){
angular.module('TimeSuck')
.controller('navigationController',["$scope","$state","$http", function($scope, $state, $http){
if(localStorage['UserData']) {
$scope.loggedIn = true;
}
else {
$scope.loggedIn = false;
}
$scope.logUserIn = function() {
$http({
method: 'POST',
url:'users/login',
}).success(function(response){
localStorage.setItem('UserData', JSON.stringify(response));
}).error(function(error){
console.log(error);
})
}
}])
})();
and the code for my html is as follows:
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<link rel="shortcut icon" href="">
<script src="node_modules/angular/angular.js"> </script>
<script src="app/app.js"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.1/angular-ui-router.js"> </script>
<script src="/app/signup/SignUpController.js"> </script>
<script src="/app/profile/edit-profile-controller.js"> </script>
<script src="/server/controllers/navigationController.js"></script>
<script src="/server/controllers/profileController.js"></script>
</head>
<body ng-app="TimeSuck" ng-controller="SignUpController">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/index.html"> Deav's Blog </a>
</div>
<ul class="nav navbar-nav">
<li> <div ng-show="!loggedIn">
Email: <input type="text" ng-model="login.email"> Password: <input type="password" ng-model="login.password">
<button type="submit" ng-click="logUserIn()"> login </button> <a ui- sref="signUp"> Create an Account </a> </li>
</ul>
<div ng-show="loggedIn"> <a ui-sref="editProfile"> </a> </div>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h1> The Smartphones </h1>
<p> This page features all the smartphones you'd want to buy and use </p>
</div>
</div>
<div ui-view> </div>
</body>
<!-- Libraries -->
<script src="node_modules/ng-file-upload/dist/ng-file-upload-all.js"></script>
<script src="node_modules/ng-file-upload/dist/ng-file-upload-shim.js"></script>
<script src="node_modules/ng-file-upload/dist/ng-file-upload.js"> </script>
Screenshot of the error:
Screenshot of the error
Why 404 error in console
In your node server ,
you defined like this one.
app.use('/app',express.static(__dirname + "/app"));
// its fine if app folder is within your root folder.
means your static resources come under app folder.
Here you,saying that your JS file come under app folder.
check second parameter.(__dirname + "/app").
So,whatever you include is script,it should contain path starts from app.
e.g.
<script src="/server/controllers/navigationController.js"></script> //its wrong
it should be
<script src="app/server/controllers/navigationController.js"></script>
In your service.js your controller paths are as follows :
'./server/controllers/profileController', './server/controllers/authenticationController'
But in your html, the paths are
<script src="/server/controllers/navigationController.js"></script>
<script src="/server/controllers/profileController.js"></script>
Are they pointing to proper paths? Pls make sure the paths are proper.
hello I am new on angular and i come again to have some help.
I try to get datas from a json file : teams.json but it doesn't work
my controller is like this :
app.controller('TeamController', ['$http', function($http){
var liste = this;
liste.teams = [];
$http.get('teams.json').success(function(data){
liste.teams = data;
});
}]);
and in my html :
<!DOCTYPE html>
<html ng-app="teamStats">
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script src="angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="TeamController">
<!--
%%%%%%%%%%%%%%%%%%%%%%%%%%% BODY CONTENT
-->
<div id="wrap" >
<div class="container">
<div >
<ul>
<li ng-repeat="team in liste.teams">{{team.name + team.win}}</li>
</ul>
</div>
</div>
</div>
<!--
%%%%%%%%%%%%%%%%%%%%%%%%%%% END OF BODY CONTENT
-->
</body>
</html>
Many thanks in advance ! hope someone see where i am wrong
I did a plunker for easier understanding
myPlunker
Best regards,
Vincent
Change your controller to this
app.controller('TeamController', ['$http', '$scope',
function($http, $scope) {
var liste = this;
$scope.liste = {};
$scope.liste.teams = [];
$http.get('teams.json').success(function(data) {
$scope.liste.teams = data;
});
}
]);
And fix your json file. You need to remove the additional ,s
Demo: http://plnkr.co/edit/jeHnvykYLwVZLsRLznRI?p=preview
Ok i think i know now why it doesn't work !! ng-repeat, ng-view, ng-include and others use AJAX to load templates. The problem is that the browser by default does not allow AJAX requests to files located on your local file system (for security reasons). Therefore you have two options:
Run local web server that will serve your files
Tell your browser to allow local files access
Thanks for help all !! Thanks to Vadim explanation !! And thanks a lot zsong ! :)