I create controller and html page And I want get http response with JSON string But I do not see nothing.
angular.module('myApp.view3', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view3', {
templateUrl: 'view3/view3.html',
controller: 'View3Ctrl'
});
}])
.controller('View3Ctrl',function($scope, $http) {
$scope.my_name = "Pasha";
$http({
method : "GET",
url : "http://api.geosvc.com/rest/US/84606/nearby?apikey=#APIKEY&d=20&pt=PostalCode&format=json"
}).then(function mySucces(response) {
$scope.myWelcome = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
It is my html page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My view</title>
</head>
<body ng-controller="View3Ctrl">
<p> Hello Pavel</p>
<div>{{my_name}}</div>
<div>{{myWelcome}}</div>
</body>
</html>
And after load page I get this result
Hello Pavel
Pasha
Angular seed app: v0.1
But I want see JSON result too
Modify your html like this.
Here you are iteration over the whole data array and printing one bye one.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My view</title>
</head>
<body ng-app="myApp.view3" ng-controller="View3Ctrl">
<p> Hello Pavel</p>
<div ng-repeat="row in myWelcome">
<div>{{row.my_name}}</div>
<div>{{row.myWelcome}}</div>
</div>
</body>
</html>
copy the url service that u want to call on the browser then, see the JSON results. U will be see that the returned JSON didn't have a data object or status text object. That's mean u can print the JSON with this code:
angular.module('myApp.view3', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view3', {
templateUrl: 'view3/view3.html',
controller: 'View3Ctrl'
});
}])
.controller('View3Ctrl',function($scope, $http) {
$scope.my_name = "Pasha";
$http({
method : "GET",
url : "http://api.geosvc.com/rest/US/84606/nearby?apikey=4ff687893a7b468cb520b3c4e967c4da&d=20&pt=PostalCode&format=json"
}).then(function mySucces(response) {
$scope.myWelcome = response;
}, function myError(response) {
$scope.myWelcome = response;
});
});
app.js
var app = angular.module('angularTable', []);
app.controller('listdata',function($scope, $http)
{
$scope.users = []; //declare an empty array
$http.get("mockJson/mock.json").success(function(response)
{
$scope.users = response; //ajax request to fetch data into
});
});
index.html
<tr ng-repeat="user in users">
<td>{{user.id}}</td>
<td>{{user.first_name}}</td>
<td>{{user.last_name}}</td>
<td>{{user.hobby}}</td>
</tr>
Related
I have an Angularjs application. In the main page I call the view with ng-view directive. I would like to hide the view in according to the value of a JS variable.
Indeed I retrieve the value of a Coldfusion SESSION variable ( that I transform in a JS variable with this instruction:
<script type="text/javascript" language="JavaScript">
<cfoutput>
var #toScript(SESSION.viewerRole, "viewerRole")#;
</cfoutput>
</script>
And I pass this variable in each controller.
I try to display the view if the value of viewRole is equal to 1 and I try to display an error message if it's not the case:
In my index.html:
<!DOCTYPE html>
<html xmlns:ng="http://angularjs.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="-1">
<script type="text/javascript" language="JavaScript">
<cfoutput>
var #toScript(SESSION.viewerRole, "viewerRole")#;
</cfoutput>
console.log("viewerRole: " + viewerRole); //OK it's working
</script>
<title>My App/title>
</head>
<body ng-app="ContactsApp" class="ng-app:ContactsApp" id="ng-app">
....................................................
<cfif #SESSION.viewerRole# eq 1>
<ng-view></ng-view>
<cfelse>
<div class="alert alert-danger">
<div>
you do not have sufficient access rights to access to this section
</div>
</div>
</cfif>
<script src="lib/js/angular.min.js"></script>
<script src="lib/js/angular-route.min.js"></script>
<script src="lib/js/angular-sanitize.min.js"></script>
<script src="app/app.js"></script>
<script src="app/appService.js"></script>
<script src="lib/js/ngDialog.js"></script>
</body>
</html>
Here my app.js:
var app=angular.module('ContactsApp', ['ngRoute', 'ui.bootstrap', 'ngDialog', 'angular-popover']);
// register the interceptor as a service
app.factory('HttpInterceptor', ['$q', '$rootScope', function($q, $rootScope) {
return {
// On request success
request : function(config) {
// Return the config or wrap it in a promise if blank.
return config || $q.when(config);
},
// On request failure
requestError : function(rejection) {
//console.log(rejection); // Contains the data about the error on the request.
// Return the promise rejection.
return $q.reject(rejection);
},
// On response success
response : function(response) {
//console.log(response); // Contains the data from the response.
// Return the response or promise.
return response || $q.when(response);
},
// On response failure
responseError : function(rejection) {
//console.log(rejection); // Contains the data about the error.
//Check whether the intercept param is set in the config array.
//If the intercept param is missing or set to true, we display a modal containing the error
if (typeof rejection.config.intercept === 'undefined' || rejection.config.intercept)
{
//emitting an event to draw a modal using angular bootstrap
$rootScope.$emit('errorModal', rejection.data);
}
// Return the promise rejection.
return $q.reject(rejection);
}
};
}]);
app.config(function($routeProvider, $httpProvider, ngDialogProvider){
console.log("CONFIG - adminRole: " + adminRole + " -- authorRole: " + authorRole + " -- viewerRole: " + viewerRole ); // It's correctly retrieved
$httpProvider.defaults.cache = false;
if (!$httpProvider.defaults.headers.get) {
$httpProvider.defaults.headers.get = {};
}
// disable IE ajax request caching
$httpProvider.defaults.headers.get['If-Modified-Since'] = '0';
// Add the interceptor to the $httpProvider to intercept http calls
$httpProvider.interceptors.push('HttpInterceptor');
$routeProvider.when('/all-contacts',
{
templateUrl: 'template/allContacts.html',
controller: 'ctrlContacts',
})
.when('/view-contacts/:contactId',
{
templateUrl: 'template/viewContact.html',
controller: 'ctrlViewContacts'
})
.otherwise({redirectTo:'/all-contacts'});
});
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
});
app.controller('ctrlContacts', function ($scope, $timeout, MyTextSearch, ContactService, RequestService, ngDialog){
$scope.adminRole = adminRole;
$scope.authorRole = authorRole;
$scope.viewerRole = viewerRole;
console.log("ctrlContacts: " + adminRole + " -- authorRole: " + authorRole + " -- viewerRole: " + viewerRole ); // It's correctly retrieved
// LOAD THE LAST REQUESTS
RequestService.loadLastRequests().success(function(lastRequests, status, header, config){
.................................
}
});
All is working but if I refresh the page with F5 I have a problem: the view is not displayed and the error message is displayed (you do not have sufficient access rights to access to this section).
Could you help me please with that?
Thank you in advance for your help
I found the origin of the problem. I put in session data in application.cfc in the function onrequeststart. But I didn't take in account the current values in session if they existed.
Now it's solved
Hi i wondering that ploblem so i want ask somebody
so please give me solution?
I make html file like that photo
but when i open this html file this file not working…
any data not diplay
what is the ploblem in this html file?enter image description here
<!doctype html>
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<div ng-controller="QueryController">
</div>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/elasticsearch-browser/elasticsearch.angular.js"></script>
<script>
var myApp = angular.module('myApp', ['elasticsearch']);
// Create the es service from the esFactory
myApp.service('es', function (esFactory) {
return esFactory({ host: 'localhost:9200'});
});
myApp.controller('ServerHealthController', function($scope, es, esFactory) {
es.cluster.health(function (err, resp) {
if (err) {
$scope.data = err.message;
} else {
$scope.data = resp;
}
});
});
// We define an Angular controller that returns query results,
// Inputs: $scope and the 'es' service
myApp.controller('QueryController', function($scope, es, esFactory) {
// search for documents
es.search({
index: 'epowersyst',
type: 'logs',
body: {
query:
{
match_all : {} }
}
}).then(function (response) {
$scope.hits = response;
console.log($scope.hits)
alert("hits값 : " + response);
});
});
</script>
</body>
</html>
In the script below, I have posted a boiled down version of my code. It's essentially a simplified search engine.
The script loops through the $scope.list_of_fruit array, and filters it according to what is typed on a simple html input text box.
<script>
var app = angular.module("myapp",[]);
app.controller("usercontroller", function($scope){
$http
.get("test.php")
.then(function (response) {
$scope.myData = response.data.records;
});
$scope.list_of_fruit = ["apple", "banana", "pear", "kiwi"];
$scope.complete = function(boxtext){
var output = [];
angular.forEach($scope.list_of_fruit, function(fruit){
if(fruit.toLowerCase().indexOf(boxtext.toLowerCase()) == 0)
{
output.push(fruit);
}
});
$scope.filteredfruit = output;
}
});
</script>
This works fine and dandy, but when I paste that http get request up top, that is completely unrelated to that $scope.complete loop, the $scope.complete loop just stops working.
Am I missing something obvious?
app.controller("usercontroller", function($scope){
You don't have $http defined, so you are probably getting an javascript error.
Add $http to the function parameters:
app.controller("usercontroller", function($scope, $http){
I created a snippet and this appears to work now
var app = angular.module('myApp', []);
app.controller("usercontroller", function($scope, $http){
$http
.get("https://jsonplaceholder.typicode.com/posts")
.then(function (response) {
$scope.myData = response.data.records;
});
$scope.list_of_fruit = ["apple", "banana", "pear", "kiwi"];
$scope.complete = function(boxtext){
console.log(boxtext);
var output = [];
angular.forEach($scope.list_of_fruit, function(fruit){
if(fruit.toLowerCase().indexOf(boxtext.toLowerCase()) == 0)
{
output.push(fruit);
}
});
$scope.filteredfruit = output;
}
});
<!DOCTYPE html>
<html ng-app='myApp'>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://rawgit.com/angular/bower-angular/master/angular.min.js"></script>
<div ng-controller="usercontroller as vm">
{{list_of_fruit}}
{{filteredfruit}}
<input type="text" ng-model="search"/>
<button ng-click="complete(search)">Do something</button>
</div>
</body>
</html>
While writing the above code in AngularJs, I am getting an error :
Error: $injector:unpr
Unknown Provider
Unknown provider: $http
I believe the reason might be while injecting $http through the serviceProvider which in my case is httpServiceProviderFunction.$inject = ["$http"];. I would appreciate if anyone could help me understand these two questions:
1) Although I have injected the $http in the httpServiceProviderFunction. Why am I getting the above error?
2)Is there any way I can inject $http in the service directly without injecting in serviceProvider? In my example, it corresponds to this line:
function httpService(url, $http) {.....}
The code snippet can be found below:
(function() {
angular.module("httpServiceApp", []).controller("httpServiceController", httpServiceControllerFunction).provider("httpService", httpServiceProviderFunction).config(configObj);
configObj.$inject = ["httpServiceProvider"]
function configObj(httpServiceProvider) {
httpServiceProvider.configuration.baseUrl = "http://davids-restaurant.herokuapp.com/categories.json";
}
httpServiceProviderFunction.$inject = ["$http"];
function httpServiceProviderFunction($http) {
var provider = this;
provider.configuration = {
baseUrl: "http://davids-restaurant.herokuapp.com/categories.json"
}
provider.$get = function() {
var service = new httpService(provider.configuration.baseUrl, $http);
return service;
}
}
function httpService(url, $http) {
var service = this;
service.menuCategories = function() {
var response = $http({
method: "GET",
url: url
});
return response;
}
}
httpServiceControllerFunction.$inject = ["httpService"]
function httpServiceControllerFunction(httpService) {
var service = httpService;
var controller = this;
var promise = service.menuCategories();
promise.then(function(response) {
controller.categories = response.data;
}).catch(function(error) {
console.log("Error occured", error);
})
}
})();
<!DOCTYPE html>
<html ng-app="httpServiceApp">
<head>
<meta charset="utf-8">
<meta name="description" content="First Angular App">
<meta name="keywords" content="HTML, Javascript, AngularJs">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.angularjs.org/1.6.1/angular.min.js"></script>
<script src="app1.js"></script>
<title>HTTP service in AngularJs</title>
</head>
<body>
<div ng-controller="httpServiceController as controller">
<div>
<ul>
<li ng-repeat="items in controller.categories">({{items.short_name}}){{items.name}}</li>
</ul>
</div>
</div>
</body>
</html>
Thank you for your time. I appreciate your help.
this my controller(MyCltr.js) it got two functions first for getting acess token and second for posting audio file to speech api , but when the second function is called the response in form of json is
{"Recognition":{"Info":{"Metrics":{"AudioBytes":0,"AudioTime":0}},"ResponseId":"c2f8054051177fb5086a9006637d8fdb","Status":"Speech Not Recognized"}}
the audio file has some recording but is showing status Speech Not Recognized.
please help me to get the text from audio file.
var MyCtrl=angular.module('MyApp.controller',[]);
MyCtrl.controller('FirstCtrl', ['$scope','$rootScope','$location','$log','$http','$window',
function($scope,$rootScope,$location,$log,$http){
$scope.files = '$audio.wav';
$scope.getToken = function () { $http({method:'POST',
url:'https://api.att.com/oauth/token',
headers:{'Content-Type':'application/x-www-form-urlencoded',
'Accept':'application/json'
},
/* data:'client_id=d3m1zlqukeyjctt5jj69jicwx4hxlpz9&client_secret=kzzwjdrvf3cugiiaycxbujqkwjfze782&grant_type=client_credentials&scope=SPEECH'*/
params: {
'client_id':'5b1cb9a9c097e1100eeeebaf66117265',
'client_secret':'01b8417ac6872450',
'grant_type':'client_credentials',
'scope':'SPEECH'
}
}
).success(function(response){
$scope.response = response;
$scope.access_token=$scope.response.access_token;
alert($scope.access_token);
var result=angular.toJson($scope.response,[true]);
alert(result);
// $scope.getText();
})
.error(function(error){
$scope.error = error;
$log.log('Its Error');
});
};
$scope.getText = function () {
$http({method:'POST',
url:'https://api.att.com/rest/2/SpeechToText',
data:$scope.files,
headers:{
'Accept':'application/json',
'Authorization':'Bearer '+$scope.access_token ,
'X-SpeechContext': 'Generic',
'Content-Type':'audio/wav'
}
}
).success(function(response){
$scope.response = response;
var result1=angular.toJson($scope.response,[true]);
alert(result1);
}).error(function(error){
$scope.error = error;
$log.error('Its error from second functionssssssssss');
});
/*$scope.getToken=function(){
$resource('https://api.att.com/oauth/token',{
'client_id':'d3m1zlqukeyjctt5jj69jicwx4hxlpz9',
'client_secret':'kzzwjdrvf3cugiiaycxbujqkwjfze782',
'grant_type':'client_credentials','scope':'SPEECH'},
{getOuth: {method: 'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'}}}).success(function(response){
$scope.response = response;
alert($scope.response);
}).error(function(error){
$scope.error = error;
alert('error');
});
};*/
};
}]);
these are the two buttons for calling the two functions, first click first then second.
<div>
<button ng-click="getToken()"> click me for Access_token</button>
<br>
<button ng-click="getText()"> click me</button>
</div>
for routing app.js is used
var MyApp=angular.module("MyApp",["MyApp.controller"]);
MyApp.config([ '$routeProvider', function ($routeProvider) {
$routeProvider.when("/First",
{
templateUrl: 'partials/First.html',
controller: 'FirstCtrl'
});
$routeProvider.otherwise({
redirectTo: '/First'
});
}]);
my index .html is like
<!DOCTYPE html>
<html ng-app="MyApp">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div ng-view></div>
<script src="lib/angular/angular.js"></script>
<script src="js/controller/MyCtrl.js"></script>
<script src="js/routing/MyApp.js"></script>
</body>
</html>
angular http data does not take a filename and read from it. It needs a string or serializable object:
data – {string|Object} – Data to be sent as the request message data. Checkout these links for help:
http://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
http://www.bennadel.com/blog/2615-posting-form-data-with-http-in-angularjs.htm