How to Fetch Wordpress Post using Angular js - angularjs

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>

Related

Call angular js function on html tag load

I am trying to call one angular js function using controller. I am using code:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DevPortal</title>
<script src="js/angular.min.js"></script>
<script src="js/controllers/app.js"></script>
</head>
<body ng-app="devportal">
<div ng-include="'templates/login_menu.html'"></div>
</body>
</html>
app.js
var app = angular.module('devportal', []);
app.controller('AppController', function($scope, $http) {
return{
getuserloginmenu : function(){$http.get('/getuserloginmenu').then(function(response){$scope.loginmenu=response.data;})},
getuserloginmenu1 : function(){$http.get('/getuserloginmenu1').then(function(response){$scope.loginmenu1=response.data;})}
};
});
login_menu.html
<div ng-controller="AppController as ctrl">
<div on-init="ctrl.getuserloginmenu()">
<p ng-repeat="menu in loginmenu">{{menu}}</p>
</div>
</div>
My rest service is working properly and returns String array. I am not able to call/get the rest service data in html.
Your code seems legit, the only thing making noise (at least for me) is the on-init you added to call the function. I think that's the problem.
Try
<div ng-controller="AppController as ctrl">
<div ng-init="ctrl.getuserloginmenu()">
<p ng-repeat="menu in loginmenu">{{menu}}</p>
</div>
</div>
And maybe.. To keep it clean: Change the syntax of the controller (even if it works)
var app = angular.module('devportal', []);
app.controller('AppController', function($scope, $http) {
$scope.getuserloginmenu = function(){$http.get('/getuserloginmenu').then(function(response){$scope.loginmenu=response.data;})};
$scope.getuserloginmenu1 = function(){$http.get('/getuserloginmenu1').then(function(response){$scope.loginmenu1=response.data;})};
});
Edit:
That's a missuse of ng-init. I'll leave the documentation of Angular for that matter
https://www.w3schools.com/angular/ng_ng-init.asp
But shortly, you want $scope.loginmenu to populate. You don't need to wait until the div loads. You can populate $scope.loginmenu right away when the controller inits.
View
<div ng-controller="AppController as ctrl">
<div>
<p ng-repeat="menu in loginmenu">{{menu}}</p>
</div>
</div>
Controller
var app = angular.module('devportal', []);
app.controller('AppController', function($scope, $http) {
$scope.getuserloginmenu = function(){$http.get('/getuserloginmenu').then(function(response){$scope.loginmenu=response.data;})};
$scope.getuserloginmenu1 = function(){$http.get('/getuserloginmenu1').then(function(response){$scope.loginmenu1=response.data;})};
$scope.getuserloginmenu();
});

restful angularjs $http get return null

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...

how to dynamically add page using ng-include with asp.net MVC using angular js

Here i am trying to call partial view from controller using angular js.
here is my code
<div ng-repeat='t in tabs'>
<div ng-include='t.templateUrl'></div>
<div>
when i try to include like ng-include="'/home/menutemplate'" it will includes the content. How can i dynamically do this? . Help me
t.templateUrl should be valid scope variable and should hold a string(path for the template):
$scope.t.templateUrl = "/home/menutemplate"
And in your template:
<div ng-include="t.templateUrl"></div>
It's exactly like what you did like this example
angular.module("app", []);
angular.module("app").controller("ctrl", function ($scope, $rootScope, $filter) {
$scope.templates = [
{url: "/Application/Partials/home.html"},
{url: "/Application/Partials/page2.html"}
]
});
<!doctype html>
<html ng-app="app" ng-controller="ctrl">
<head>
</head>
<body>
<div class="container">
<div ng-repeat="temp in templates">
<div ng-include="temp.url"></div>
</div>
<script type="text/ng-template" id="/Application/Partials/home.html">
<h1>home.html is here</h1>
</script>
<script type="text/ng-template" id="/Application/Partials/page2.html">
page 2 is here
</script>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
</body>
</html>

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

AngularJS consuming REST Service

I need to code an AngularJS page which displays some JSON data coming from a REST Service.
The REST service when invoked displays this JSON example data:
[{"key":"ABX1234","value":"Network Hub"}]
Here is the HTML page that I'm using to retrieve the data:
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script>
function Hello($scope, $http) {
$http.get('http://host/json').
success(function(data) {
$scope.json = data;
});
}
</script>
</head>
<body>
<div ng-controller="Hello">
<p>The ID is {{json.key}}</p>
<p>The content is {{json.value}}</p>
</div>
</body>
</html>
Unfortunately nothing is displayed as json.key or json.value. Can you help me to find out what is the issue ?
Thanks!
It should be like this:
<div ng-controller="Hello">
<div ng-repeat="json in json">
<p>The ID is {{json.key}}</p>
<p>The content is {{json.value}}</p>
</div>
</div>
You are getting array of objects. It needs to be iterated.

Resources