Display a list with Angular - angularjs

I have the following code:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script type="text/javascript">
var application = angular.module('Application');
application.controller('ImageController', function ImageController($scope, $http) {
$scope.result = "Start here ...";
$http.get('api/images').
success(function (data, status, headers, config) {
$scope.images = data;
$scope.result = "Everything is ok";
}).
error(function (data, status, headers, config) {
$scope.result = "Something went wrong";
});
});
</script>
<div ng-app="Application" ng-controller="ImageControler">
<p>{{result}}</p>
<div ng-repeat='image in images'>
<span>{{image.votes}}</span>
</div>
</div>
What I get on the rendered HTML page is {{result}} and {{image.votes}} like Angular was not working ... I also checked the API and it is not called ...
What am I missing?

You have spelling mistake in <div ng-app="Application" ng-controller="ImageControler">
Controller with 2 L's

Related

Why is it that the data from the $http service cannot be obtained?

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>First AngularJS Application</title>
<script src="scripts/angular.js"></script>
</head>
<body ng-app = "myAngularApp">
<div>
<div ng-controller="myController">
Response Data: {{data}} <br />
Error: {{error}}
</div>
</div>
<script>
var myApp = angular.module('myAngularApp', []);
myApp.controller("myController", function ($scope, $http) {
var onSuccess = function (data, status, headers, config) {
$scope.data = data;
};
var onError = function (data, status, headers, config) {
$scope.error = status;
}
var promise = $http.get("index.html");
promise.success(onSuccess);
promise.error(onError);
});
</script>
</body>
This is the html file and when I load the page the data were not retrieved. I'm not sure if I have some little mistakes since I copy pasted it in the tutorial.
This will be the output.
Folder Structure
The script tag is wrong in your case. You are using lowercase in your code but your folder structure shows uppercase Scripts
<script src="Scripts/angular.js"></script>
Update
If you are using latest version of angularjs, try the below code since success and error are deprecated.
var myApp = angular.module('myAngularApp', []);
myApp.controller("myController", function ($scope, $http) {
var onSuccess = function (data) {
$scope.data = data.data;
};
var onError = function (data) {
$scope.error = data;
}
var promise = $http.get("index.html");
promise.then(onSuccess);
promise.catch(onError);
});
For more Info : Why are angular $http success/error methods deprecated? Removed from v1.6?
Use then rather than success and use catch rather than error
Example:
<div>
<div ng-controller="myController">
Response Data: <span ng-bind-html="data"></span> <br />
Error: {{error}}
</div>
</div>
<script>
var myApp = angular.module('myAngularApp', []);
myApp.controller("myController", function ($scope, $http, $sce) {
var onSuccess = function (data, status, headers, config) {
$scope.data = $sce.trustAsHtml(data.data);
};
var onError = function (data, status, headers, config) {
$scope.error = data;
}
var promise = $http.get("index.html");
promise.then(onSuccess);
promise.catch(onError);
});
</script>

Angular injector error with Filestack

I am attempting to integrate Filestack into an existing app. I think I am having issues with how those modules are configured, but can't get the ordering correct. I receive this error:
angular.js:38Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.6/$injector/modulerr?p0=myApp&p1=TypeError%…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.6%2Fangular.min.js%3A20%3A156)
Here is the routing file:
(function () {
var app = angular.module('myApp', ['ngRoute', 'angular-filepicker']);
// ROUTING
app.config(['$routeProvider', function($routeProvider, filepickerProvider){
$routeProvider
.when('/home', {
templateUrl: "views/home.html",
controller: "HomeController"
})
.when('/shopping-list/:id', {
templateUrl: "views/shopping-list.html",
controller: 'ShoppingListController'
})
.when('/add-list', {
templateUrl: "views/add-list.html",
controller: 'AddListController'
})
.otherwise({
redirectTo: '/home'
});
filepickerProvider.setKey('XXXXXXX');
}]);
Here is the index.html:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<!-- CDN SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/randomcolor/0.4.4/randomColor.min.js"></script>
<!-- Font Awesome -->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">
<!-- Bootstrap -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Tara's Custom CSS -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<!-- Imported Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Rubik" rel="stylesheet">
<title>Shopping List</title>
</head>
<body>
<div ng-include="'partials/header.html'"></div>
<main ng-view></main>
<!--ANGULAR SCRIPTS-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-animate.min.js"></script>
<script src="/bower_components/filepicker-js/filepicker.js"></script>
<script src="/bower_components/angular-filepicker/dist/angular_filepicker.js"></script>
<script type="text/javascript" src="//api.filestackapi.com/filestack.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/controllers/controller-header.js"></script>
<script type="text/javascript" src="js/controllers/controller-home.js"></script>
<script type="text/javascript" src="js/controllers/controller-add-list.js"></script>
<script type="text/javascript" src="js/controllers/controller-shopping-list.js"></script>
</body>
</html>
And the controller that is using Filestack:
(function () {
'use strict';
var app = angular.module('myApp');
app.controller('ShoppingListController', ['$scope', '$http', '$routeParams', 'API_BASE', '$location', function($scope, $http, filepickerService, $routeParams, API_BASE, $location){
// GET SPECIFIC LIST
$scope.list = [];
var id = $routeParams.id;
$http({
method: 'GET',
url: API_BASE + 'shopping-lists/' + id
}).then(function successCallback(response) {
$scope.list = response.data[0];
}, function errorCallback(response) {
console.log('it did not work');
console.log(response.statusText);
});
// REMOVE LIST
$scope.removeList = function(){
var id = $scope.list.id;
console.log(id);
$http.delete(API_BASE + 'shopping-lists/' + id)
.success(function (data, status, headers, config) {
console.log('you deleted :' + $scope.list);
})
.error(function (data, status, header, config) {
});
$location.path('/home');
};
// RANDOM ID
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 20; i++ ){
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
text += Date.now();
return text;
}
// ADD ITEM
$scope.addItem = function(){
var created = new Date();
var newID = makeid();
if($scope.list.hasOwnProperty('items') === false){
$scope.list.items = [];
}
$scope.list.items.push({
name : $scope.newItem.name,
priority : $scope.newItem.priority,
note: $scope.newItem.note,
picture: $scope.newItem.picture,
isChecked: false,
listId: $scope.list.id,
created: created,
id: newID
});
// console.log($scope.list.items);
$http.put(API_BASE + 'shopping-lists/', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
// Reset input fields after submit
$scope.newItem = {
name: "",
priority: "",
note: ""
};
};
// ADD ITEM IMAGE
$scope.upload = function(){
filepickerService.pick(
{
mimetype: 'image/*',
language: 'en',
services: ['COMPUTER','DROPBOX','GOOGLE_DRIVE','IMAGE_SEARCH', 'FACEBOOK', 'INSTAGRAM'],
openTo: 'IMAGE_SEARCH'
},
function(Blob){
console.log(JSON.stringify(Blob));
$scope.newItem.picture = Blob;
$scope.$apply();
});
};
// REMOVE ITEM
$scope.removeItem = function(item){
var removedItem = $scope.list.items.indexOf(item);
$scope.list.items.splice(removedItem, 1);
$http.put(API_BASE + 'shopping-lists', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
};
// CLEAR ITEMS
$scope.clearItems = function(){
$scope.list.items.length = 0;
$http.put(API_BASE + 'shopping-lists', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
};
// CLEAR CHECKED ITEMS
$scope.clearCheckedItems = function(){
var length = $scope.list.items.length-1;
for (var i = length; i > -1; i--) {
if ($scope.list.items[i].isChecked === true) {
$scope.list.items.splice(i,1);
}
}
$http.put(API_BASE + 'shopping-lists', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
};
//Edit Items / Checked Items
$scope.editItem = function(){
$http.put(API_BASE + 'shopping-lists', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
};
// SORT ITEMS
$scope.sortBy = function(propertyName) {
$scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
$scope.propertyName = propertyName;
};
}]);
}());
Right now, I can't get the page to load at all. Something isn't being called properly, I just can't figure out how to get the page to load (getting the Filestack to function properly is secondary right now).
Any suggestions with the configuration?
You do not have to declare a module for your controller,
var app = angular.module('myApp');
Change like this also you are missing 'filepickerService' while inecting,
angular.module('myApp').controller('ShoppingListController', ['$scope', '$http','filepickerService', '$routeParams', 'API_BASE', '$location', function($scope, $http, filepickerService, $routeParams, API_BASE, $location){

Can not sign in with google in angular

i am trying angular for the first time. i am trying to sign in with google account. But It is not working. When i load the page the button appears and then after loading it hides. and the code is not working to.
here is my app.html
<body >
<div ng-app="app" ng-controller="AppCtrl as app">
<button ng-click="update()">Post data</button>
</div>
<div ng-controller="SignCtrl">
<span id="signinButton" >
<span class="g-signin" ng-click="signIn()"></span>
</span>
<button onclick="SignedOut();">SignedOut</button>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script type="text/javascript" src="appMy1.js"></script>
<script type="text/javascript" src="GSignIn.js"> </script>
</body>
Here is my controller
var app = angular.module("app", []);
app.factory("GPlusAuthService", function ($q, $window) {
var signIn;
signIn = function () {
var defered = $q.defer();
$window.signinCallback = function (response) {
$window.signinCallback = undefined;
defered.resolve(response);
};
gapi.auth.signIn({
clientid: "389760997134-uredjv5rat0k3vsjaqlt7nn4pbgtqrat.apps.googleusercontent.com",
cookiepolicy: "single_host_origin",
requestvisibleactions: "http://schemas.google.com/AddActivity",
scope: "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read",
callback: "signinCallback"
})
return defered.promise;
};
return {
signIn: signIn
}
});
app.controller("AppCtrl", function($scope,$http) {
$scope.update=function(){
$http.post("/user/signup",{Name:'Mr.x',Email:'AX#gmail.com',Organisation:'Ruet',PlacesLived:'dhaka',Img_url:'xyz'})
.success(function(data, status, headers, config) {
console.log(headers);
})
.error(function(data, status, headers, config) {
//console.log(data);
console.log(headers);
});
}
}),
app.controller('SignCtrl', function ($scope, GPlusAuthService) {
$scope.signIn = function() {
GPlusAuthService.signIn().then(function(response) {
});
}
});
Any clue what i am doing wrong?
The error is "cookiepolicy is a required field". But i have mentioned the cookiepolicy.

Disallow multiple votes on image on an angular list

I have the following Angular and HTML code to display a list of images and allow voting:
<script type="text/javascript">
var application = angular.module('Application', []);
application.service('ImageService', function ($http) {
return {
GetList: function (page) {
return $http.get('api/images', { params: { page: page } });
},
Vote: function (image) {
return $http.post('api/images/{key}/vote', { key: image.Key });
}
}
});
application.controller('ImageController', function ImageController($scope, ImageService) {
var page = 0;
$scope.images = [];
ImageService.GetList(page)
.success(function (data, status, headers, config) {
$scope.images = $scope.images.concat(data);
})
.error(function (data, status, headers, config) { });
$scope.vote = function (image) {
ImageService.Vote(image)
.success(function (data, status, headers, config) { })
.error(function (data, status, headers, config) { });
};
});
</script>
<div data-ng-app="Application" data-ng-controller="ImageController" class="gallery">
<div data-ng-repeat='image in images' class="image">
<img src="{{image.Url}}" alt="" />
<i class="icon-heart"></i>
<span>{{image.Votes}}</span>
</div>
</div>
Each image has an unique id, image.Id.
How can I disallow a user to vote the same image twice?
Use ng-hide to hide link if hasVoted is true.
<div class="gallery">
<div data-ng-repeat='image in images' class="image">
<img src="{{image.Url}}" alt="" />
<i class="icon-heart"></i>
<span>{{image.Votes}}</span>
</div>
</div>
Then modify controller to set voted to true. If it fails we will set it back to false. The reason to do it is to prevent multiple clicks on the button until we receive success back from the server:
$scope.vote = function (image) {
image.hasVoted = true;
ImageService.Vote(image)
.success(function (data, status, headers, config) { })
.error(function (data, status, headers, config) { image.hasVoted = false; });
};
The simplest tweak on the client side would be something like this:
$scope.vote = function (image) {
if (!image.voted) {
ImageService.Vote(image)
.success(function (data, status, headers, config) { image.voted = true })
.error(function (data, status, headers, config) { });
}
};
Simply flag the image as voted.

Load Next Page in Angular

I have the following Angular and HTML code:
<script type="text/javascript">
var application = angular.module('Application', []);
application.service('ImageService', function ($http) {
return {
GetList: function () {
return $http.get('api/images');
},
}
});
application.controller('ImageController', function ImageController($scope, ImageService) {
ImageService.GetList()
.success(function (data, status, headers, config) {
$scope.images = data;
})
.error(function (data, status, headers, config) { });
});
</script>
<div data-ng-app="Application" data-ng-controller="ImageController" class="gallery">
<div data-ng-repeat='image in images' class="image">
<img src="{{image.Url}}" alt="" />
</div>
</div>
The API call is returning the following:
[
{"Key":"89207","Url":"http://somedomain.com/image89207.jpg"},
{"Key":"12321","Url":"http://somedomain.com/image12321.jpg"},
{"Key":"23434","Url":"http://somedomain.com/image23434.jpg"}
]
I would like to load the next page when the user scrolls down to the end of the page or when it clicks a button saying "Show More".
I also need to return on my JSON the NextPage value ...
The point is that if current page is "233" then next page might be "4545".
I think the API might need to return the next page value and a list of images.
How can I do this?
I agree with pankajparkar. You should handle 'show more' button, load more images and join it with $scope.images. ng-repeat will do remaining work. Here is code sample
<script type="text/javascript">
var application = angular.module('Application', []);
application.service('ImageService', function($http) {
return {
GetList: function(page) {
return $http.get('api/images', {
params: {
page: page
}
});
},
}
});
application.controller('ImageController', function ImageController($scope, ImageService) {
var page = 0;
$scope.images = [];
var load = function() {
ImageService.GetList(page)
.success(function(data, status, headers, config) {
$scope.images = $scope.images.concat(data);
})
.error(function(data, status, headers, config) {});
};
load();
$scope.loadMore = function() {
page++;
load();
}
});
</script>
<div data-ng-app="Application" data-ng-controller="ImageController" class="gallery">
<div data-ng-repeat='image in images' class="image">
<img src="{{image.Url}}" alt="" />
</div>
<div>
<button ng-click="loadMore()">load more</button>
</div>
</div>

Resources