connect AngularJS to mysql using my PHP service?

后端 未结 2 789
天涯浪人
天涯浪人 2020-12-15 12:46

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 ha

相关标签:
2条回答
  • 2020-12-15 13:19

    OK. Solved it. First, copied and added a controller I found in one of the examples:

        function FetchCtrl($scope, $http, $templateCache) {
            $scope.method = 'GET';
            $scope.url='../services/index.php';  
            $scope.fetch = function() {
                $scope.code = null;
                $scope.response = null;
    
                $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
                success(function(data, status) {
                    $scope.status = status;
                    $scope.data = data;
                }).
                error(function(data, status) {
                    $scope.data = data || "Request failed";
                    $scope.status = status;
                });
            };
    
            $scope.updateModel = function(method, url) {
                $scope.method = method;
                $scope.url = url;
            };
        }
    

    Then, I added a route controller to my module:

    var module = angular.module('Cats', ['ngResource','Cats.filters', 'Cats.services', 'Cats.directives'])
        .config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/main', {templateUrl: 'partials/partial1.html', controller: MyCtrl1});
    

    Finally, on that partial1.htm page, I added this:

    <div ng-init="fetch()">
        {{data}}
    </div>
    

    Now when I go to that page in the browser, I can see the entire database dumped out in JSON. Ahhhh. Clearly there are many more sophisticated things to try, etc etc but I needed this simple result so I could be certain that I did in fact have a model arriving when summoned. Angular dies silently in many cases, so a visible result was quite helpful.

    One gotcha: be careful that the php file is executable by more than yourself as user. I don't know the name of the user that AngularJS implements but I had to chmod 644 index.php so the app could use it.

    I hope that helps someone.

    0 讨论(0)
  • 2020-12-15 13:33

    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

    0 讨论(0)
提交回复
热议问题