Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

connect AngularJS to mysql using my PHP service?

I am using AngularJS 1.0, PHP, and mysql with localhost on my Mac.

I have a very simple mysql database: "cats". It has one table called "kittens". The table has two columns, "id" and "name". There are three kittens in the database with names Larry, Curly, and Moe.

Now, I have some simple PHP code which opens the dbase, gets the three records, and returns them in JSON like this: [{"id":"1","name":"Larry"},{"id":"2","name":"Curly"},{"id":"3","name":"Moe"}]

I used the latest angular-seed and set up a project in Eclipse. In app.js I wrote this: 'use strict'; angular.module('Cats', ['ngResource','Cats.filters', 'Cats.services', 'Cats.directives']) I put my PHP code in the services folder and named it "index.php". If I navigate to that services/index.php in my browser using localhost on the Mac, I get back the JSON above. So far everything is cool.

Now - ALL I WANT TO DO (!famous last words ;) is connect to the PHP service I have and display the contents of that Cats table on my main index page using my AngularJS project. Plain old text, no tables, just bind to the available resource and display it.

I have tried all manner of demos online (many are out of date). Can anyone show me one simple, current way to do this? For the life of me I have all kinds of AngularJS demos working but none of them does this simple task in a way I can understand.

Thank you in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This should also work. It's significantly fewer lines of code, but note that any error handling has been removed:

function FetchCtrl($scope, $resource) {
  var services = $resource('../services/index.php');
  $scope.data = services.query();
}
FetchCtrl.$inject = ['$scope', '$resource'];

Normally I would have used the built in .get() method on the $resouce but your response is in the form of an Array, which .query() supports by default.

You can find the documentation on $resource here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...