angularJS function in controller does not respond - javascript

AngularJs ng-click does not respond
I'm trying to use the GitHub Search-API.
When someone click the button my Controller should call a search from github here is my code
HTML:
<head>
<script src="js/AngularJS/angular.min.js"></script>
<script src="js/Controller/RepoController.js"></script>
</head>
<body ng-controller="RepoController">
<input type="text" ng-model="param" /><button ng-click="search()">suchen</button>
<ul>
<li ng-repeat="repo in repos">
{{repo.name}}
</li>
</ul>
</body>
and here is my controller:
var App = angular.module('RepoSearch', []);
function RepoController($scope, $http) {
$scope.repos = [];
$scope.search = function() {
$http.get('https://api.github.com/search/repositories?q='+$scope.param).success(function(data) {
$scope.repos = data['items'];
}
}
}
but my repos-array is still empty
when I swap the $http.get with an alert it is working fine.

You forgot to close ( after $scope.repos = data['items'];}, and to define ng-app, which in this case, can be in <head> : <head ng-app="RepoSearch">
http://docs.angularjs.org/api/ng.directive:ngApp

The reason could be cross domain call. Use JSONP to call into github.
$http.jsonp('https://api.github.com/search/repositories?q='+$scope.param+'&callback=JSON_CALLBACK'+).success(function(data) {
$scope.repos = data['items'];
}
The callback method maybe different so look at these SO posts
Using angularjs JSONP when callback cant be defined
Using JSONP method for $http service in AngularJS

In HTML
<head ng-app="RepoSearch">
<script src="js/AngularJS/angular.min.js"></script>
<script src="js/Controller/RepoController.js"></script>
</head>
<body ng-controller="RepoController">
<input type="text" ng-model="param" /><button ng-click="search()">suchen</button>
<ul>
<li ng-repeat="repo in repos">
{{repo.name}}
</li>
</ul>
</body>
in Controller
var App = angular.module('RepoSearch', []);
//bind controller with your app
App.controller('RepoController',RepoController);
function RepoController($scope, $http) {
$scope.repos = [];
$scope.search = function() {
$http.get('https://api.github.com/search/repositories?q='+$scope.param).success(function(data) {
$scope.repos = data['items'];
}
}
}

Related

How to get data from rest api which has basic authentication?

I'm trying to get data from this website through HTTP get method. This website has basic authentication. The data is in JSON format.
This is the rest api website:
(https://shoploapi.herokuapp.com/sellers)
// Code goes here
angular.module('myapp', ['myapp.controller']);
angular.module('myapp.controller', ['myapp.service'])
.controller('testController', function($scope, testService) {
$scope.posts = {};
function GetAllPosts() {
var getPostsData = testService.getPosts();
getPostsData.then(function(post) {
$scope.posts = post.data;
}, function() {
alert('Error in getting post records');
});
}
GetAllPosts();
});
angular.module('myapp.service', [])
.service('testService', function($http) {
//get All NewsLetter
this.getPosts = function() {
return $http.get('https://shoploapi.herokuapp.com/sellers');
};
});
angular.module('myApp', ['base64'])
.config(function($httpProvider, $base64) {
var auth = $base64.encode("bhupendra7:ice123age456");
$httpProvider.defaults.headers.common['Authorization'] = 'Basic ' + auth;
});
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.5.0" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-base64/2.0.5/angular-base64.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body ng-app="myapp">
<h1>Hello Plunker!</h1>
<div ng-controller="testController">
<div>
<ul>
<li ng-repeat="post in posts">
{{post.careof}} {{post.district}} {{post.gender}} {{post.name}}
</li>
</ul>
</div>
</div>
</body>
</html>
Here's the link to my Plunker:
(https://plnkr.co/edit/7pqljm?p=preview)
Can anyone help?
There are 2 problems in your code.
1. You have a typo
In angular.module('myApp', ['base64']), change to module name to myapp
2. The way you have injected your myapp.controller to myapp module
Change it to angular.module('myapp', []); You will also need to reorder your code. Check out the Plunker I have created for you.
Even if you fix the above two problems, you will still face a CORS problem from Heroku. Depending on your server-side technology (NodeJS, Rails etc.), you will need to enable it from the server to be able to communicate with your app. You can also look in to JSONP with AngularJS
Hope this helps

Calling anonymous method recursively in angular controller method

I want to send ajax requests at regular intervals from the angular controller method. for that i have written code like below.
var mainApp = angular.module('myapp',[]);
mainApp.controller('controller', function($scope,$http,$window,$timeout) {
$('#radioBtn a').on('click', function(){
$http({
method:,
url:,
params:{parameters}
}).then(function(success){
},function(error){
});
$timeout(function(){
//how to call the anonymous function passed to $('#radioBtn a').on() here.
},30000);
});
I am not getting how to call the anonymous method from timeout function. Using this() is failing.
First off: Don't bind to element clicks like that, use the ng-click directive - in fact, just don't even load jQuery in your application, in 99% cases you're better off without it.
Second: Use angular's $interval service. Check the code sample below.
angular.module('app', [])
.controller('ctrl', function($scope, $interval) {
$scope.numbers = [];
$scope.startInterval = function() {
$scope.interval = $interval(function() {
$scope.numbers.push($scope.numbers.length);
}, 1000)
}
})
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.6.0" data-semver="1.6.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app" ng-controller="ctrl">
<button ng-if="!interval" ng-click="startInterval()">Start polling</button>
<div ng-repeat="number in numbers">
{{number}}
</div>
</body>
</html>
try this way.
var mainApp = angular.module('myapp',[]);
mainApp.controller('controller', function($scope,$http,$window,$interval) {
$('#radioBtn a').on('click', function(){
$interval(function(){
$http({
method:,
url:,
params:{parameters}
}).then(function(success){
},function(error){
});
},30000);
});

REST call in AngularJS does not display record

This is my first AngularJS project. I followed this website to create a simple html to display a single record by calling restful services. The rest works with the url "http://localhost:8080/api/seqs/fdebfd6e-d046-4192-8b97-ac9f65dc2009".
Here is my html:
<html ng-app="cgApp" ng-controller="CgseqCtrl">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-resource.js"></script>
<script src="../js/controller.js"></script>
</head>
<body>
<div>
<hr>
<h2>{{seq.analysisId}}</h2>
<h2>{{seq.library}}</h2>
</hr>
</div>
</body>
</html>
I defined the resource in a service js
//service.js
angular.module('cgApp', ['ngResource'])
.factory('CgseqService', function ($resource) {
return $resource('http://localhost:8080/api/seqs/fdebfd6e-d046-4192-8b97-ac9f65dc2009',
{get: {method: 'GET'}
});
});
The controller:
//controller.js
angular.module('cgApp', ['ngResource'])
.controller('CgseqCtrl', ['CgseqService', '$scope', function (CgseqService, $scope)
{
$scope.getSeq = function(response) {
CgseqService.get(function(data) {
$scope.seq = data;
});
};
}]);
When I started my http server with Node.js and typed the url in the browser, nothing is displayed. What did I do wrong?
Several errors.
You didn't load your factory code. It looks like you only loaded your controller.js (I'm assuming your factory code is in a different file since in your example you commented it as //service.js):
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-resource.js"></script>
<script src="../js/controller.js"></script>
</head>
np-controller should say ng-controller:
<html ng-app="cgApp" np-controller="CgseqCtrl">
You also never called your $scope.getSeq function:
$scope.getSeq = function(response) {
CgseqService.get(function(data) {
$scope.seq = data;
});
};
You should call $scope.getSeq() somewhere to actually invoke it.

Angularjs function inside ng-repeat called too many times

I've got a function in my controller very easy that just stamp a console.log. I need to conditioning a button using a function but inside the ng-repeat the controller repeats everything many times! Is it normal? Is it possible avoid this? Thanks. An example here http://plnkr.co/edit/sME67gQEZQSLI9FOwEAG?p=preview
relative code:
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.4.5" data-semver="1.4.5" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="DigestApp">
<div ng-controller="UserCtrl as uc">
<h1>Please open the console to see</h1>
<ul>
<li ng-repeat="user in uc.users" ng-class="uc.userClasses(user)">
{{user.name}}
<button ng-if="uc.isUserEnabled(user)"
ng-click="uc.disableUser(user)">Disable</button>
</li>
</ul>
</div>
</body>
</html>
javascript:
angular.module("DigestApp", [])
.controller('UserCtrl', function(User) {
var vm = this;
vm.users = User.list();
vm.isUserEnabled = function(user) {
console.log('isUserEnabled');
return user.active;
};
vm.userClasses = function(user) {
console.log('userClasses');
return []
.concat(user.active ? ['user-active'] : [])
.concat(user.loggedIn ? ['user-logged-in'] : [])
.concat(user.isMe ? ['user-is-me'] : [])
.join(' ');
};
vm.disableUser = function(user) {
user.active = false;
};
})
.factory('User', function() {
return {
list: function() {
return [{
name: "me",
active: true,
loggedIn: true,
isMe: true
}];
}
};
});
Yes, this is normal. There is no way that angular can tell whether the result of the function will have changed, so it calls it on every digest loop. If you want to avoid that you should calculate the value once and set the result as an attribute on the user object.
<li ng-repeat="user in uc.users" ng-class="user.classes">
{{user.name}}
<button ng-if="user.active"
ng-click="uc.disableUser(user)">Disable</button>
</li>
and in the controller add some code to precalculate a user.classes attribute on each user object (and to update it when you change the state of the model).
Please update your li in the HTML to the below. I got it working here http://plnkr.co/edit/Cx5OZaY0dhmBT4WLYZpX?p=info.
<li ng-repeat="user in uc.users" ng-class="{ 'user-active': user.active, 'user-logged-in': user.loggedin, 'user-is-me': user.isme }">
{{user.name}}
<button ng-if="user.active" ng-click="uc.disableUser(user)">Disable</button>
</li>
By using a function in your ng-class and ng-if it was evaluating to often. You can just pass the scope variables instead.

AngularJS error: fnPtr is not a function

I'm trying to write a sample AngularJS, and SpringMVC project. The spring methods works fine, but I have a problem with declaraton of function in my site controller. My app should return a word from text input, but when I click the button, I've got this error:
[13:23:58.900] "Error: fnPtr is not a function
parser/_functionCall/<#http://localhost:8080/example/resources/js/Angular/angular.js:6542
ngEventDirectives[directiveName]</</</<#http://localhost:8080/example/resources/js/Angular/angular.js:13256
Scope.prototype.$eval#http://localhost:8080/example/resources/js/Angular/angular.js:8218
Scope.prototype.$apply#http://localhost:8080/example/resources/js/Angular/angular.js:8298
ngEventDirectives[directiveName]</</<#http://localhost:8080/example/resources/js/Angular/angular.js:13255
createEventHandler/eventHandler/<#http://localhost:8080/example/resources/js/Angular/angular.js:2095
forEach#http://localhost:8080/example/resources/js/Angular/angular.js:130
createEventHandler/eventHandler#http://localhost:8080/example/resources/js/Angular/angular.js:2094
"
This is my index.html:
<!DOCTYPE html>
<html lang="en" ng-app="Apken">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="resources/js/Angular/angular.js"></script>
<script src="resources/js/controler.js"></script>
</head>
<body ng-controller="theNamer">
<div class="input-append">
<input style="width:358px;" class="span2" type="text" ng-model="myName" required min="1" />
<button class="btn btn-primary" ng-disabled="!myName" ng-click="send()">Click!</button>
</div>
<ul>
<li ng-repeat="name in names">{{name}}</li>
</ul>
</body>
</html>
And controler.js:
function theNamer ($scope,$http){
$scope.myName='aa';
$scope.fetchList=new function()
{
$http.get('ca/list.json').success(function(thList){
$scope.names = thList;
});
}
$scope.send=new function()
{
$http.post('ca/set/3').success(function(){
$scope.fetchList;
});
}
$scope.fetchList;
}
var Apken = angular.module('Apken',[]);
Apken.controller('theNamer', theNamer);
I've noticed, that must be a some kind of problem with function declaration in the ng-click value. On site startup controler.js works fine, but it crashes, when I click the button.
Just wanted to add for anybody receiving this error, it can also be seen if you, like me, make the n00b mistake of creating a variable with the same name as function (the function being called from ng-click:
$scope.addTask = {};
$scope.addTask = function() {};
I have tested your code. Using AngularJS 1.0.7, the error disappears when you replace
$scope.send = new function() {
with
$scope.send = function () {
and same applies to fetchList.
I guess you mixed the two syntaxes function(*args*) { *body* } and new Function(*args*, *body*). Check on MDN: Function.
You have also to change your code in order to get your fetchList properly called:
function theNamer($scope, $http) {
$scope.myName = 'aa';
$scope.fetchList = function() {
$http.get('ca/list.json').success(function(thList) {
$scope.names = thList;
});
};
$scope.send = function() {
$http.post('ca/set/3').success(function() {
$scope.fetchList();
});
};
$scope.fetchList();
}

Categories

Resources