I wrote some Angular JS code by learning from a tutorial. But in that video tutorial, the code works properly, but my code is not working. My web page is showing a blank page.
The index.html:
<div body ng-app="angularTable">
<div class="all_cat_main" ng-controller="listdata">
<div class="all_cat" ng-repeat="state in statelist">
<h2>{{state.Satename}}</h2>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="~/Content/AppJS/AllSate.js"></script>
And the AllSate.js
var app = angular.module('angularTable', []);
app.controller('listdata', function ($scope, $http) {
$scope.statelist = [];
$.ajax({
url: "/JobWebApi/getDataForAngularGrid",
dataType: 'jsonp',
method: 'GET',
data: '',
})
.success(function (response) {
$scope.statelist = response;
})
.error(function (error) {
alert(error);
});
});
Please someone guide me why the code is not working ?
Please Remove injected $http from Controller and Firstly Load Jquery lib file.(http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js)
var app = angular.module('angularTable', []);
app.controller('listdata', function ($scope) {
$scope.statelist ="";
$.ajax({
url: "http://api.geonames.org/weatherIcaoJSON?ICAO=LSZH&username=demo",
dataType: 'jsonp',
method: 'GET',
data: '',
}).success(function (response) { debugger;
$scope.statelist = response.status;
$scope.$apply();
})
.error(function (error) {
alert(error);
});
});
<html ng-app="angularTable">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body ng-controller="listdata">
<div >
<div >
<h2>{{statelist.message}}</h2>
</div>
</div>
</body>
</html>
Related
Hello i need to show the response from a website (200, 404, etc) using REST services.
i have created a partial code but i dont know how show the result
This is js
angular.module('demo', [])
.controller('Hello', function($scope, $http) {
$http ({
method: 'GET',
url: 'http:/www.google.com'
}).
then(function(response) {
$scope.greeting = response.data;
});
})
and this is html
<body>
<div ng-controller="Hello">
<p>Result = {{greeting.content}}</p>
</div>
</body>
</html>
Thanks for help.
You should really be putting your $http calls into a separate service and injecting that into the controller.
so something like this:
angular.module('demo')
.factory('greetingService', function($http) {
this.getGreeting = function() {
return $http ({
method: 'GET',
url: 'http:/www.google.com'
}).then(function(response) {
return response.data
});
}
};
Then inject the service into your controller and call greetingService.getGreeting and then set your $scope variable to the result.
Also make sure you have the proper headers in your request.
The response is a IHttpPromise<T> which extends IPromise<IHttpPromiseCallbackArg<T>>.
The interface for this looks like this:
interface IHttpPromiseCallbackArg<T> {
data?: T;
status?: number;
headers?: IHttpHeadersGetter;
config?: IRequestConfig;
statusText?: string;
}
So you can access what you need with:
response.status
With your code:
angular
.module('demo', [])
.controller('Hello', HelloController)
function HelloController($scope, $http) {
$http({
method: 'GET',
url: 'http://enable-cors.org'
})
.then(function(response) {
var text = "The status: " + response.status;
$scope.directResponse = response;
$scope.greeting = {content: text};
$scope.someVariable = text;
});
}
/*
var $http = angular.injector(["ng"]).get("$http");
$http.get("http://enable-cors.org/").then(function(response) {
console.log(response.status);
});
*/
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo" ng-controller="Hello">
<p>Status = {{directResponse.status}}</p>
<p>Result = {{greeting.content}}</p>
<p>Result = {{someVariable}}</p>
</div>
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.
I'm trying to use the Bing maps REST api from within angular. Fiddler shows a 200 response for both requests below, but Angular fails both, the $hhtp with "No Access-Control-Allow-Origin header is present' and the $request with "Unexpected token : "
I've not tried to do a cross-origin request with angular before but clearly I'm missing something. Any help would be appreciated.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular-resource.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="myctrl"></div>
<script type="text/javascript">
var myapp = angular.module('myapp', ['ngResource']).config(['$httpProvider', function ($httpProvider) {
// delete header from client:
// http://stackoverflow.com/questions/17289195/angularjs-post-data-to-external-rest-api
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
myapp.controller('myctrl', ["$scope", "$resource", "$http", function ($scope, $resource, $http) {
var t = $resource('http://dev.virtualearth.net/REST/v1/Locations?locality=Redmond&adminDistrict=WA&key=MAPKEY&o=json',
{
callback: 'JSON_CALLBACK'
}, {
jsonpquery: { method: 'JSONP', isArray: false }
});
var x = t.jsonpquery().$promise;
debugger;
x.then(function (data) {
debugger;
console.log(data);
});
$http.get('http://dev.virtualearth.net/REST/v1/Locations?locality=Redmond&adminDistrict=WA&jsonp=jsonp&key=MAPKEY')
.success(function(data) {
debugger;
})
.error(function(data, status, error, thing) {
debugger;
console.log(data);
});
}]);
</script>
</body>
</html>
You'll need a map key from https://www.bingmapsportal.com/ to make a request though.
Any help appreciated, otherwise I'll drop down to using jQuery
Use $http.jsonp instead of $http.get. The following code works:
var url = "http://dev.virtualearth.net/REST/v1/Locations?locality=Redmond&adminDistrict=WA&jsonp=JSON_CALLBACK&key=YOUR_BING_MAPS_KEY";
$http.jsonp(url)
.success(function (data) {
debugger;
})
.error(function (data, status, error, thing) {
debugger;
console.log(data);
});
i'm trying to upload image file along with it's details information with AngularJS. The file's details will be stored in JSON file on the server. But, it doesn't work. the return info from the server is just an empty array. I have no idea why my code doesn't work. I to experiment with Content-type, etc, etc... but still no luck.
my code:
<body>
<div>
<form ng-controller="Ctrl" ng-submit="save()">
Title :<input type="text" ng-model="file_details.title"><br>
Summary: <input type="text" ng-model="file_details.summary"><br>
File: <input type="file" file-upload><br>
<button type="submit">save</button>
</form>
</div>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/angular/angular.min.js"></script>
<script>
//Angular here
(function(){
var app = angular.module('myApp', []);
app.config(function($httpProvider){
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
app.controller('Ctrl', ['$scope', '$http', function($scope, $http){
$scope.file_details = {};
$scope.files = [];
//listening from fileUpload directive
$scope.$on('fileSelected', function(event, args){
$scope.$apply(function(){
//add the file object to scope's files collection
$scope.files.push(args.file);
});
});
$scope.save = function(){
$http({
method: 'POST',
url: 'process.php',
transformRequest: function (data) {
var formData = new FormData();
formData.append("file_details", angular.toJson(data.file_details));
formData.append("file", data.files);
},
headers: {
'Content-Type': false
},
data: {
file_details: $scope.file_details,
files: $scope.files
}
}).success(function (data, status, headers, config) {
// alert("success!");
console.log(data);
});
}
}]);
app.directive('fileUpload', function(){
return{
link: function(scope, elm, attrs){
elm.bind('change', function(event){
var files = event.target.files;
scope.$emit('fileSelected', { file: files });
});
}
}
});
})();
</script>
</body>
My server code (just to check if the data is sent, but it still returning an empty array):
print_r($_POST); die();
**Does anyone know how you can check to see that a resource failed to be fetched in AngularJS?
error:
Error: [ng:areq]
http://errors.angularjs.org/undefined/ng/areq?p0=PhotoListCtrl&p1=not%20a%20function%2C%20got%20undefined
**
<html ng-app>
<head>
<title>angularjs</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
<script type="text/javascript" src="Scripts/jquery-1.9.1.min.js"></script>
</head>
<body ng-controller="PhotoListCtrl">
<h1>Angular js</h1>
<p>Nothing here {{'yet' + '!'}}</p>
<button title="list" ng-click="list()">list</button>
<button title="copy" ng-click="copy()" >copy</button>
<ul >
<li ng-repeat="photo in photos">
<img src="{{'data:image/png;base64,' + photo.Image}}" title="{{photo.Name}}"></img>
</li>
</ul>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular-resource.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular-route.min.js"></script>
<script type="text/javascript">
var app= angular.module('myApp', ['ngResource']).factory('dataservice', function ($resource) {
return $resource('/applicationdata.svc/Photos/:id', {id:'#id'}, {
query: { method: 'GET', isArray: true },
get: { method: 'GET', params: {id:0} },
remove: { method: 'DELETE' },
edit: { method: 'PUT' },
add: { method: 'POST' }
});
});
app.controller('PhotoListCtrl', ['$scope', 'dataservice', function ($scope, dataservice) {
$scope.photos = [];
$scope.list = function () {
dataservice.query({}, function (data) {
$scope.photos = data.value;
});
};
}]);
//function PhotoListCtrl($scope ,$http) {
// $http.get('/applicationdata.svc/Photos').success(function (data) {
// $scope.photos = data.value;
// });
// $scope.orderProp = 'Name';
// $scope.copy = function () {
// $http.post('/applicationdata.svc/Photos', $scope.photos[0]).success(function (data) {
// console.log(data);
// });
// }
//}
</script>
</body>
</html>