restful angularjs $http get return null - angularjs

I'm trying AngularJS for the first time. I'm getting as imple user JSON data from a http-get request, but the object is returned null. I tested my service using chrome and I get this result:
[{"id":1,"email":"walid#gmail.com","name":"walid"}]
Below my js file:
var app = angular.module("userApp", []);
app.controller("userController", function($scope, $http) {
$scope.user = null;
$scope.name = null;
$scope.getUser = function() {
$http({
method : 'GET',
url : '/all',
}).success(function(data) {
$scope.user = json.stringify(data);
}).error(function(data) {
alert('Fail: user is '+data);
});
}
});
My HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>SIM Card</title>
<link rel="Stylesheet" type="text/css"
href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
<link rel="Stylesheet" type="text/css" href="css/simcard.css">
<script type="text/javascript" src="angular/angular.min.js"></script>
<script type="text/javascript" src="js/simcard2.js"></script>
<script type="text/javascript" src="js/json2.js"></script>
</head>
<body ng-app="userApp" ng-controller="userController">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-info spacer">
<div class="panel-heading">User Management</div>
<div class="panel-body">
<form action="">
<div class="form-group">
<label>ID</label> <input type="text" ng-model="email">
<button ng-click="getUser()" type="submit">Save</button>
</div>
</form>
</div>
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-info spacer">
<div class="panel-heading">Result</div>
<div class="panel-body">
<div class="form-group">
<label>Name: </label>
<label>{{user.name}}</label>
</div>
</div>
</div>
</div>
</body>
</html>
I can send the whole maven project in case needed. Thank you for your help.
Regards,
Walid

you can do it like this:
var app = angular.module("userApp", []);
app.controller("userController", function($scope, $http) {
$scope.getUser = function() {
return $http.get('/all').then(
function successCallback(response) {
// you can log response here to see what it is
// or you can simply check network in your browser DevTools
$scope.users = response;
},
function errorCallback(response) {
alert('There was error retrieving users List');
}
);
};
});
once that is done based on your response which is an array you can repeat it in your view. ngRepeat is also watching your model update so every time you update $scope.users it will update itself.
So you can simply use this in your view:
<div ng-app="userApp" ng-controller="userController">
<ul>
<li ng-repeat="user in users">
<span> {{user.id}} {{user.name}} {{user.email}} </span>
</li>
</ul>
</div>
The benefit of using $http.get(...).then() is that you can you can use promise chain with ease to build other services on top of this. In your case you have to make sure that you check your response.
// Update :
Here's a Bin that you can see the code above in action: https://jsbin.com/luguzu/1/edit
Just in output hit Run with js and click Get Users.

The problem is in your config of the request:
http://plnkr.co/edit/qEkpUAXQQZmO9iUAZ2aX?p=preview
It doesn't know what type of data you expect in response.
Your http request should look like this:
$http.get("test.json").success(function(data) {
$scope.user = data[0];
}).error(function(data) {
alert('Fail: user is 2 '+data);
});
Update:
Just noticed something in yout HTML - you have there a form with action empty. This is the cause of the request being canceled.
in angularjs to have a form, it is enought to add to a div ng-form="myForm" and the input can be just simple button, not submit and it is going to work fine.

Here it is the image of my network console...

Related

Passing Data between state Providers in angular

Im looking to pass data between 2 controllers in Angular, Below is code i started
There are 2 views one with input field and other with a link.
when i click on link in the second view i should be able to set a state and state data should be populated in input field in first field.
I tried several approaches but im missing something.
Can someone help me here
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Hello AngularJS</title>
<script data-require="angular.js#1.2.10" data-semver="1.2.10" src="http://code.angularjs.org/1.2.10/angular.min.js"></script>
<script src="http://angular-ui.github.io/ui-router/release/angular-ui-router.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', ['ui.router']);
myApp.config(['$stateProvider','$stateProvider', '$urlRouterProvider', function ($stateProvider,$urlRouterProvider) {
var addBook = {
name: 'addBook',
url: '/addBook',
template: '<h2>Add A book</h2> Data from View <input type="text" ng-model={{input-text}}>' ,
data:""
},
viewBookv = {
name: 'viewBookv',
url: '/viewBook',
template: '<h2>View A book</h2><span class="glyphicon glyphicon-edit">Edit</span> ' ,
};
$stateProvider.state(addBook, "controller: editUserCtrl");
$stateProvider.state(viewBookv, "controller: editUserCtrl");
}])
myApp.controller('editUserCtrl', function($scope, $stateParams) {
$scope.paramOne = $stateParams.data;
$scope.edit = function () {
event.preventDefault();
$state.go("addBook");
}
})
myApp.controller('mainController',function($scope, $rootScope, $state,$window){
$scope.addBook=function(){
$state.go("addBook");
};
$scope.viewbookls= function(){
$state.go("viewBookv");
};
})
</script>
</head>
<body>
<div class="container">
<div class="col">
<div class="col-md-3" ng-controller="mainController">
<ul class="nav">
<li> View Book </li>
<li> Add Book </li>
</ul>
</div>
<div class="col-md-9">
<div ui-view></div>
</div>
</div>
</div>
</body>
</html>
Typically in angular the way to share state between controllers is using a service. So the way it's usually set up is to setup a service then import that service into the relevant controllers, and that data gets shared between them. I've modified your example above to follow this pattern(I'm not quite sure what you were trying to do)
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Hello AngularJS</title>
<script data-require="angular.js#1.2.10" data-semver="1.2.10" src="http://code.angularjs.org/1.2.10/angular.min.js"></script>
<script src="http://angular-ui.github.io/ui-router/release/angular-ui-router.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', ['ui.router']);
myApp.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider,$urlRouterProvider) {
var addBook = {
name: 'addBook',
url: '/addBook',
template: '<h2>Add A book</h2> Data from View <button ng-click="updateBook()">Update</button> <input type="text" ng-model="inputText">' ,
controller: "addBookCtrl",
data:""
},
viewBookv = {
name: 'viewBooks',
url: '/viewBook',
template: '<h2>View A book</h2><div ng-repeat="book in bookList">{{book}}</div>',
controller: "viewBookCtrl",
};
$stateProvider.state('addBook', addBook);
$stateProvider.state('viewBooks', viewBookv);
}])
myApp.controller('addBookCtrl', function($scope, bookService) {
$scope.updateBook = function(){
console.log( $scope.inputText)
bookService.books.push($scope.inputText);
}
})
myApp.controller('viewBookCtrl', function($scope, bookService) {
$scope.bookList = bookService.books
})
myApp.factory('bookService', function() {
var bookService = {};
bookService.books = [];
return bookService;
});
myApp.controller('mainController',function($scope, $rootScope, $state,$window){
$scope.addBook=function(){
$state.go("addBook");
};
$scope.viewbookls= function(){
$state.go("viewBooks");
};
})
</script>
</head>
<body>
<div class="container">
<div class="col">
<div class="col-md-3" ng-controller="mainController">
<ul class="nav">
<li> View Book </li>
<li> Add Book </li>
</ul>
</div>
<div class="col-md-9">
<div ui-view></div>
</div>
</div>
</div>
</body>
</html>
What this example does, is in the text box for add book, you type in the name (then click update), this appends it to an array so every time you do it you'll get a new element on that array. From there head over to the view books page, and you'll see all the different things you typed in.

How to get data from JSON using Angularjs?

var app = angular.module("app", []);
app.controller('emp', ['$scope', 'empService', function($scope, empService){
$scope.doSearch = function(){
empService.findEmployeeById($scope.searchempno, function(r){
$scope.empno = r.empno;
$scope.ename = r.ename;
$scope.salary = r.salary;
$scope.dptno = r.dptno;
});
};
}]);
app.service('empService', ['$http', '$log', function($http, $log){
this.findEmployeeById = function(empno, cb){
$http({
url: 'employees.json' + empno,
method: 'GET'
}).then(function(resp){
cb(resp.data);
});
};
}]);
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-app="app">
<div ng-controller="emp">
<form class="form-inline">
<div class="form-group">
<label>Enter Employee Number:</label>
<input type="text" class="form-control" ng-model="searchEmpno"/>
</div>
<button class="btn btn-primary" ng-click="doSearch()">Search</button>
</form>
<hr>
<div class="row">
<div class="col-sm-2">Employee No</div>
<div class="col-sm-2">{{empno}}</div>
</div>
<div class="row">
<div class="col-sm-2">Employee Name</div>
<div class="col-sm-2">{{ename}}</div>
</div>
<div class="row">
<div class="col-sm-2">Salary</div>
<div class="col-sm-2">{{salary}}</div>
</div>
<div class="row">
<div class="col-sm-2">Deptno</div>
<div class="col-sm-2">{{dptno}}</div>
</div>
</div>
</body>
</html>
If I gave the number in input field like 1001 and click the search button. It will not show the details. I have checked the console, there is no error. My JSON file has been placed the same location of the HTML file.
Thanks,
SamBhishma
I have created an updated plunker here. First issue was what I mentioned in the comment. In your view, you are writing <input type="text" class="form-control" ng-model="searchEmpno"/>and in your controller, you're trying to access this variable as searchempno
Second issue is in your http request. You cannot pick and choose the data from json file based on the id. You have to get the entire JSON file, parse it and filter out the value if it matches your searchEmpno model value. I fixed it in the plunker.
Third issue, you are attaching plain values to your scope like $scope.empno , $scope.ename. Instead, you need to put such values into an object, so in your controller, put the matched employee object in the scope and in your view, reference it as {{obj.ename}} and so on.
Another thing, no need to return callbacks inside then. The clean way of handling successful, failed http calls is:
$http.get('url').then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Read more about them here.
Take a look at the updated plunker to see if it matches your needs.
Problem is your model variable is wrong inside the view, try this
<input type="text" class="form-control" ng-model="searchEmpno"/>
DEMO

How to Fetch Wordpress Post using Angular js

I 'am trying to connect my angular app to WordPress CM using wordpress rest api plugin and through $http Service However, for some reason data doesn't return.Can someone provide the correct method for retrieving data for wordpress using wordpress rest api plugin?
Below I have listed my code that includes my html and JavaScript. Also, I have listed the the local rest api that I'm trying to get my test data .
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.6.2/angular-sanitize.js"></script>
</head>
<body>
<div class="masthead" np-app="myApp">
<div class="item">
<div class="masthead-content">
<div class="copy">
<div class="container">
<div class="row">
<div class="col-md-6" ng-controller="Ctrl">
<div ng-repeat="post in posts | limitTo: 1">
<h2 ng-bind-html="post.title.rendered">{{posts}}</h2>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
var app = angular.module('myApp', ['ngSanitize']);
app.controller('myCtrl', function($http, $scope) {
$http.get("http://localhost/wp/wp-json/wp/v2/posts/4").success(function(data) {
$scope.posts = data;
});
});
</script>
I have no problem with calling rest API of WordPress
$http.get('https://yourblog.com/wp-json/wp/v2/posts/?categories=1&per_page=2&orderby=id&order=asc&page=1').
then(function(response) {
console.log(response);
$scope.posts = response.data;
});
this code run in my AngularJS or ionic app
<div ng-repeat="post in posts">
<h2>{{post.title}}</h2>
</div>

How to "bind" the HTML representation to a controller

I'm reading through some docs and books about Angular, but I don't really find an angular way of the following problem:
If I have a controller (let's say CardController), and another controller which handles the creation of multiple instances of the CardController. How should I implement the HTML-stuff? I want to be able to instantiate a Card, which has a specific HTML-code (like the one below) and is connected to the CardController.
I don't think that I should pollute the CardController to setup the HTML stuff with ugly .append-stuff. Or is this the way? Should I write an extra service for the HTML representation like CardView or create an extra directive?
If you look at this example, I want to be able to click on "Add another card" and see another instance of a card added below (so basically the ability to have multiple items):
<!DOCTYPE html>
<html ng-app="theApp">
<head>
<script data-require="angular.js#1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-controller="MainController">
<button ng-click="add()">Add another card</button>
</div>
<div id="content">
<div ng-controller="CardController">
<h1>{{ title }}</h1>
<p>{{ message }}</p>
</div>
</div>
<script>
(function() {
var app = angular.module("theApp", []);
app.controller('MainController', function($scope) {
$scope.add = function() {
// Setup HTML for TheController:
// add another DIV/H1/P-etc. to #content,
// just like the one at the beginning.
console.log("Add another card");
};
});
app.controller('CardController', function($scope) {
$scope.title = "A Title";
$scope.message = "Some message";
});
}());
</script>
</body>
</html>
Try this code from my snippet:
(function() {
var app = angular.module("theApp", []);
app.controller('MainController', function($scope) {
var iter = 1;
$scope.cards = [{
id: 1
}];
$scope.add = function() {
$scope.cards.push({
id: ++iter
});
// Setup HTML for TheController:
// add another DIV/H1/P-etc. to #content,
// just like the one at the beginning.
console.log("Add another card");
};
});
app.controller('CardController', function($scope) {
$scope.title = "A Title";
$scope.message = "Some message";
});
}());
<!DOCTYPE html>
<html ng-app="theApp">
<head>
<script data-require="angular.js#1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body ng-controller="MainController">
<div>
<button ng-click="add()">Add another card</button>
</div>
<div id="content">
<div ng-repeat="card in cards" ng-controller="CardController">
<h1>{{ title }}</h1>
<p>{{ message }}</p>
</div>
</div>
</body>
</html>
There is few options. For example you can use angular directives (for me this is the most elegant solution) and create HTML structure like this:
<div ng-controller="MainController">
<button ng-click="add()">Add another card</button>
<div id="content">
<your-card-directive ng-repeat="card in cards" card-data="card"></your-card-directive>
</div>
</div>
or use ng-include to load HTML from your HTML files:
<div ng-controller="MainController">
<button ng-click="add()">Add another card</button>
<div ng-repeat="card in cards" ng-controller="CardController as CardCtrl" ng-include="'../../your-card-template.html'"></div>
</div>
or just use inline HTML:
<div ng-controller="MainController">
<button ng-click="add()">Add another card</button>
<div ng-repeat="card in cards" ng-controller="CardController">
<h1>{{ title }}</h1>
<p>{{ message }}</p>
</div>
</div>
one approach
<div ng-repeat="test in tests>{{test}}</div>
$scope.tests = ["Test Message","Test Message 2"];
$scope.tests.push("new msg");
this vl automatically create a div and ur list grows
or
http://blog.sodhanalibrary.com/2014/08/append-or-prepend-html-to-div-using.html#.Vhz-NxOqqko

Angular, data in one controller filter to this data in other

At start i want to say im new in angular. Lets say my page look like this:
index.html:
<body ng-app="application">
<div class="container">
<div class="row">
<div class="col-sm-3 sideBar" ng-controller="NavController">
<input ng-model"search">
</div>
<div class="col-sm-9 content" ng-controller="ContentController">
<div ng-repeat="meet in meets | filter:search">
{{ meet.someData }}
</div>
</div>
</div>
</div>
</body>
And how can i make that input in NavController could filter data from ContentController? I want to do this in two controllers.
I'm not sure why you want to do this in two controllers, but it will be considerably more difficult. The Search functionality acts on the data in the content controller. I am guessing that your layout is driving your controller design.
There are numerous posts here that discuss techniques for this. This one: Share data between AngularJS controllers is well-regarded.
Actually you can just do that in a single controller.
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.name = [{
"id":1
},{
"id":2
},{
"id":3
}]
});
<!DOCTYPE html>
<html ng-app="angularjs-starter">
<head lang="en">
<meta charset="utf-8">
<title>Custom Plunker</title>
<script src="//code.angularjs.org/1.1.1/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl"><input ng-model='find' />
<div ng-repeat="x in name | filter : find">
{{x.id}}
</div>
</body>
</html>
For understanding, i used numbers as data. :) Hope it helps you
You can have a parent controller over the other two controllers. If you use the controllerAs method you can have controllers inside each other, see Angular Style Guide for helpful information about controllers and controllerAs.
You could write it like that and bind the search model to the ParentController.
Edit: I added another solution that I think is better
var app = angular.module('app', []);
app.controller('ParentController', function() {
this.search = 'p'; //set default just for fun
});
app.controller('NavController', function() {
//nav stuff
});
app.controller('ContentController', function() {
this.meets = [{
data: 'hi'
}, {
data: 'potato'
}, {
data: 'help me'
}, {
data: 'pie'
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div class="container" ng-controller="ParentController as parentVm">
<div class="row">
<div class="col-sm-3 sideBar" ng-controller="NavController as navVm">
<input ng-model="parentVm.search">
</div>
<div class="col-sm-9 content" ng-controller="ContentController as contentVm">
<div ng-repeat="meet in contentVm.meets | filter:parentVm.search">
{{ meet.data }}
</div>
</div>
</div>
</div>
</body>
I stepped away from this for a bit and thought of another idea that doesn't involve using another controller. Here you are using a factory instead to communicate between the controllers. You have to share an object so that when you change the search.term in the input it will change for every reference.
var app = angular.module('app', []);
app.factory('Searcher', function() {
return {
search: {
term: 'p'
}
};
});
app.controller('NavController', function(Searcher) {
//nav stuff
this.search = Searcher.search;
});
app.controller('ContentController', function(Searcher) {
this.search = Searcher.search;
this.meets = [{
data: 'hi'
}, {
data: 'potato'
}, {
data: 'help me'
}, {
data: 'pie'
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div class="container">
<div class="row">
<div class="col-sm-3 sideBar" ng-controller="NavController as navVm">
<input ng-model="navVm.search.term">
</div>
<div class="col-sm-9 content" ng-controller="ContentController as contentVm">
<div ng-repeat="meet in contentVm.meets | filter:contentVm.search.term">
{{ meet.data }}
</div>
</div>
</div>
</div>
</body>

Resources