AngularJS using JSONP data issue - angularjs

I have got a problem displaying content from jsonp request:
function ContentCtrl($scope, $http) {
"use strict";
$scope.url = 'domain/api/getposts/?auth_key=s2mEus39R296M5F6n343A3dh9c62f7cm&custom_post=updates&callback=JSON_CALLBACK';
$scope.content = [];
$scope.fetchContent = function() {
console.log($scope.url);
$http.get($scope.url).then(function(result){
$scope.content = result.data;
});
};
$scope.fetchContent();
}
and my html template is:
<div id="container" ng-controller="ContentCtrl">
<content-item ng-repeat="item in content" content="item">{{item.ID}}
</content-item>
</div>
Am I doing anything wrong? Really apprecite your help...

Related

How can i execute angular script after onclick event

Here is my html code:
<div ng-app="myApp" ng-controller="customersCtrl">
<p id="druzyny"></p>
</div>
and then in angular script:
var app = angular.module('myApp', []);
document.getElementById("search1").onclick = app.controller('customersCtrl', function($scope, $http){
var place = document.getElementById("place").value;
var sel1 = document.getElementById("sel1").value;
var sel2 = document.getElementById("sel2").value;
var req = {
method: 'post',
url: 'findTournament',
headers: {
'Content-type': 'application/json'
},
data: {place: 'test'}
};
$http(req).then(function(response){
});
});
I`ve got button id="search1" and i want that angular execute only when i click this button, no automatically when page is reload, is it possible?
Thanks for answears
HTML:
<div ng-app="myApp" ng-controller="customersCtrl as customers">
<input data-ng-model="customers.place">
<input data-ng-model="customers.sel1">
<input data-ng-model="customers.sel2">
<button data-ng-click="customers.init()"></button>
</div>
JS:
angular.module('myApp', []);
angular
.module('myApp')
.controller('customersCtrl', function($scope, customersService){
var vm = this;
vm.init = function(){
customersService.findTournament({place: vm.place, sel1: vm.sel1, sel2: vm.sel2})
.then(function(res){});
};
});
angular
.module('myApp')
.service('customersService', function($http){
return {
findTournament: findTournament
};
function findTournament(data){
return $http.post('findTournament', data);
}
});

Angularjs: Cannot display array items using ng-repeat

I am using AngularJs to retrieve the data from ASP.Net Controller.
The Json data is retrieved from the server, but can't figure out why cannot display array items when using the ng-repeat:
var app = angular.module('Appp', []);
app.controller('metadataCtrl', function ($scope, $http) {
$scope.lookupItems = {};
$http({ method: 'GET', url: '/home/listvalues?listid=3' }).then(function (response) {
$scope.lookupItems = response;
console.log($scope.lookupItems);
},
function (error) { alert("error"); });
// console.log($scope.listItems);
});
<form name="myForm" ng-controller="metadataCtrl" class="my-form">
<div ng-repeat="item in lookupItems">
{{$index}}
{{item.ListValueID}}
</div>
</form>
The Json Retrieved from the server:
[{"ListValueID":13,"Translation":{"TranslationID":0,"Value":"Important","LanguageValues":{"ar":"مهم","en":"Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":14,"Translation":{"TranslationID":0,"Value":"Less Importance","LanguageValues":{"ar":"أقل أهمية","en":"Less Importance"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":15,"Translation":{"TranslationID":0,"Value":"Very Important","LanguageValues":{"ar":"كثير الأهمية","en":"Very Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0}]
The most likely issue (assuming that your app and controller are constructed and referenced properly) is that the object returned from the promise contains a .data property which actually holds your JSON data.
Try this:
$http({ method: 'GET', url: '/home/listvalues?listid=3' })
.then(function (response) {
$scope.lookupItems = response.data;
console.log($scope.lookupItems);
},
function (error) {
alert("error");
});
I think you just forgot to wrap your app with ng-app:
var app = angular.module('Appp', []);
app.controller('metadataCtrl', function ($scope, $http) {
$scope.lookupItems = {};
$scope.lookupItems = [{"ListValueID":13,"Translation":{"TranslationID":0,"Value":"Important","LanguageValues":{"ar":"مهم","en":"Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":14,"Translation":{"TranslationID":0,"Value":"Less Importance","LanguageValues":{"ar":"أقل أهمية","en":"Less Importance"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":15,"Translation":{"TranslationID":0,"Value":"Very Important","LanguageValues":{"ar":"كثير الأهمية","en":"Very Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0}];
console.log($scope.lookupItems);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="Appp">
<form name="myForm" ng-controller="metadataCtrl" class="my-form">
<div ng-repeat="item in lookupItems">
{{$index}}
{{item.ListValueID}}
</div>
</form>
</body>
You probably misspelled Appp. Make sure your module definition in your javascript:
var app = angular.module('App', []); //Changed to App from Appp
matches your app declaration in your html
<div ng-app="App">
...controller declaration...
...body.....
</div>

How to get results with angular.js $http?

I'm getting some problem getting the results from my api server with angularjs.
This is my code:
home.html (view)
<div class="jumbotron text-center">
<h1>Home Page</h1>
<p>{{ message }}</p>
Orders!
</div>
<ul>
<li ng-repeat="order in orders">{{order}}</li>
</ul>
main.js (controller)
app.controller('mainController', function($scope, $http) {
$scope.message = 'Everyone come and see how good I look!';
$scope.orders = [];
$scope.getOrders = function(){
$http.get('http://apidemo.dev/api/orders').success(function(response){
console.log("My data: " + response);
$scope.orders = response;
});
}
});
When I click the button, I can see the results in the console, but not in the list.
If use this code in the controller, it works when it loads, and when I click the button:
app.controller('mainController', function($scope, $http) {
$scope.message = 'Everyone come and see how good I look!';
$http.get('http://apidemo.dev/api/orders').success(function(response){
console.log("My data: " + response);
$scope.orders = response;
});
$scope.getOrders = function(){
$http.get('http://apidemo.dev/api/orders').success(function(response){
console.log("My data: " + response);
$scope.orders = response;
});
}
});
What is the problem ?
Thanks!
Seems like you were using ngRoute and you have href="#" in your anchor, which leads you redirection to blank page, Keep href="" will help you in css to show pointer: cursor; on hover of it
Button
Orders!
Thanks everybody for your help.
The problem was the link in the view...
Orders!
would be:
<a ng-click="getOrders()">Orders!</a>

Can't send a POST request with $http in Angular - ReferenceError: $http is not defined

So I keep getting this ReferenceError: $http is not defined, even though I have included $http in the controller, which seems to be the most common cause of this error message. I've tried also passing $http into the function itself, but that doesn't solve it.
I feel like I am missing something SUPER obvious, so any help would be much appreciated, thank you!
I've included the entire script, just for clarity's sake. You can see the post request towards the end of the script, inside the finaliseDay function.
Thanks!
Here is the error:
ReferenceError: $http is not defined
at l.$scope.finaliseDay (http://localhost:8888/goalzy.js:69:12)
at ib.functionCall (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:198:303)
at Dc.(anonymous function).compile.d.on.f (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:214:485)
at l.$get.l.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:125:305)
at l.$get.l.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:126:6)
at HTMLAnchorElement.<anonymous> (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:215:36)
at HTMLAnchorElement.c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:32:389)angular.js:11607 (anonymous function)angular.js:8557 $getangular.js:14502 $get.l.$applyangular.js:21440 (anonymous function)angular.js:3014 c
Here is the HTML first
<!doctype html>
<html ng-app="goalzy">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>
<script src="goalzy.js"></script>
</head>
<body>
<div class="container">
<div class="well">
<h2>Goalzy</h2>
Dev TODO
<ul>
<li>Hook up the API to persist data</li>
</ul>
<div ng-controller="TodoController">
<span>{{remaining()}} of {{todos.length}} remaining today</span>
<span>You're at {{percentComplete()}}% completion</span>
[ finalise day ]
<ul class="unstyled">
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</li>
</ul>
<form ng-submit="addTodo()">
<input type="text" ng-model="todoText" size="30"
placeholder="add new todo here">
<input class="btn-primary" type="submit" value="add">
</form>
<hr>
<div class="historial" ng-repeat="h in historicalDailyPercentages">
<ul>
<li>Date: {{h.date}}</li>
<li>Percentage of Daily Tasks Completed: {{h.percent}}%</li>
<li><div>Tweet it!</div></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
And here is the JS:
//Goalzy.js
angular.module('goalzy', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
});
.controller('TodoController', ['$scope','$http', function($scope, $http) {
$scope.todos = [];
$scope.historicalDailyPercentages = [];
$scope.addTodo = function() {
if ($scope.todoText != "") {
if ($scope.todos.length < 3) {
$scope.todos.push({text:$scope.todoText, done:false});
$scope.todoText = '';
//Save to DB
}
else {
alert("You can only have 3 todos per day!");
$scope.todoText = '';
}
} else {
alert("you must write something");
}
};
$scope.remaining = function() {
var count = 0;
angular.forEach($scope.todos, function(todo) {
count += todo.done ? 0 : 1;
});
return count;
};
$scope.percentComplete = function() {
var countCompleted = 0;
angular.forEach($scope.todos, function(todo) {
countCompleted += todo.done ? 1 : 0; //Simply calculates how many tasks have been completed
console.log(countCompleted);
});
var totalCount = $scope.todos.length;
var percentComplete = countCompleted / totalCount * 100;
return percentComplete;
}
$scope.finaliseDay = function(percentComplete) {
alert("You're finalising this day with a percentage of: " + percentComplete);
var today = new Date();
var alreadyPresent = $scope.historicalDailyPercentages.some(function (item) {
return item.date.getFullYear() === today.getFullYear() &&
item.date.getMonth() === today.getMonth() &&
item.date.getDate() === today.getDate();
});
//Confirm that nothing has alreayd been posted for today
if (!alreadyPresent) {
$scope.historicalDailyPercentages.push({
percent: percentComplete,
date: today
});
// Simple POST request example (passing data) :
$http.post('/api/postDailyPercentage.php', {msg:'hello word!'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("data" + data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log("data" + data);
});
}
else {
alert("You're all set for today - see you tomorrow!");
}
console.log($scope.historicalDailyPercentages);
}
}]);
Provider won't be available inside controller with suffix 'Provider', you can do access them by provider name only here it would be $http only, also remove ;
after config initialization
$httpProvider setting should be done inside the angular config phase
CODE
angular.module('goalzy', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
}]);
.controller('TodoController', ['$scope', '$http', function($scope, $http) {
//controller code here
}]);
Note: For sure you should remove $httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8'; line from controller
Working Plunkr
You don't have to use "$httpProvider" in controller, use $http instead.
e.g.
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
As best practice, do not configure provider ($http) in controller. Do it in config section. as below
var app = angular.module('goalzy', []);
app.config(function ($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
});
app.controller('TodoController', ['$scope','$http', function($scope, $http) {
$scope.title="scope title";
//$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
}]);
see working plunk at http://run.plnkr.co/plunks/4mY4izqc48P8wVQFumZ8/ with your html.

Working with two modules in AngularJS

I have two modules with different operations and I tried to work with them as shown below.
<div id="viewBodyDiv" ng-app="xhr">
<div ng-controller="xhrCtrl">
<button ng-click="callAction()">Click</button>
{{sample}}
</div>
</div>
<div id="viewBodyDiv2" ng-app="xhr2">
<div ng-controller="xhr2Ctrl">
<button ng-click="alertMessage()">Click</button>
</div>
</div>
The JS is shown below.
angular.module('xhr', []).controller('xhrCtrl', function ($http, $scope, $window) {
$scope.sample = "sadf";
$scope.callAction = function () {
$http({
method: 'GET',
url: 'Angular/GetData',
params: {
api_key: 'abc'
}
}).then(function (obj) { //I get a text result that I display near the button
$scope.sample = obj.data;
});
};
});
angular.module('xhr2', []).controller('xhr2Ctrl', ['$window','$scope',
function ($window,$scope) {
$scope.alertMessage = function () {
$window.alert("xhr2Ctrl clicked");
};
}]);
When I click on the viewBodyDiv I am getting the desired output but when I click on viewBodyDiv2 the alert message is not getting displayed.
I am new to AngularJS and please let me know what I am doing wrong or what it the procedure to work with two different Modules in Angular.
Thank you.
add this code to the bottom of your JavaScript
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById('viewBodyDiv2'),['xhr2']);
});
Hope this helps.
As per the AngularJS documentation:
https://docs.angularjs.org/api/ng/directive/ngApp
Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application.
However, if you still want to do it this way, you have to use angular.boostrap() manually to achieve this. Here is a good tutorial on this:
http://www.simplygoodcode.com/2014/04/angularjs-getting-around-ngapp-limitations-with-ngmodule/
So you need to bootstrap the module to have multiple angular apps on the same page.
You can also inject one of the modules into another.
var xhrModule = angular.module("xhr", ["xhr2"]);
Following is a sample code for bootstrapping the module.
<html>
<head>
<script src="angular.min.js"></script>
</head>
<body>
<div id="viewBodyDiv" ng-app="xhr">
<div ng-controller="xhrCtrl">
<button ng-click="callAction()">Click</button>
{{sample}}
</div>
</div>
<div id="viewBodyDiv2" ng-app="xhr2">
<div ng-controller="xhr2Ctrl">
<button ng-click="alertMessage()">Click</button>
</div>
</div>
<script>
var xhrModule = angular.module("xhr", []);
xhrModule.controller('xhrCtrl', function ($http, $scope, $window) {
$scope.sample = "sadf";
$scope.callAction = function () {
$http({
method: 'GET',
url: 'Angular/GetData',
params: {
api_key: 'abc'
}
}).then(function (obj) { //I get a text result that I display near the button
$scope.sample = obj.data;
});
};
});
var xhr2Module = angular.module("xhr2", [])
xhr2Module.controller('xhr2Ctrl', ['$window','$scope',
function ($window,$scope) {
$scope.alertMessage = function () {
$window.alert("xhr2Ctrl clicked");
};
}]);
angular.bootstrap(document.getElementById("viewBodyDiv2"),['xhr2']);
</script>

Resources